public static string GetUsersWithProducts(ProductShopContext context) { var usersCount = context.Users .Where(x => x.ProductsSold.Count >= 1) .Count(); var users = context .Users .Where(u => u.ProductsSold.Count > 0) .OrderByDescending(u => u.ProductsSold.Count) .Select(u => new ExportSoldProductDto { FirstName = u.FirstName, LastName = u.LastName, Age = u.Age, SoldProducts = u.ProductsSold .Select(sp => new UserProductsSoldDto { Count = u.ProductsSold.Count(), Products = u.ProductsSold .Select(user => new SoldProductDto { Name = user.Name, Price = user.Price }) .OrderByDescending(x => x.Price) .ToArray() }) .ToArray() }) .Take(10) .ToArray(); var s = new UsersCountDto { Count = usersCount, Users = users }; var xmlSerializer = new XmlSerializer(typeof(UsersCountDto)); var sb = new StringBuilder(); var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); xmlSerializer.Serialize(new StringWriter(sb), s, namespaces); return(sb.ToString().TrimEnd()); }
//08. Export Users and Products public static string GetUsersWithProducts(ProductShopContext context) { var usersWithSellsCount = context.Users .Where(u => u.ProductsSold.Any()); var userSoldProductsDtos = usersWithSellsCount .OrderByDescending(u => u.ProductsSold.Count) .Take(10) .Select(u => new UserSoldPruductsDto { FirstName = u.FirstName, LastName = u.LastName, Age = u.Age, SoldProducts = new SoldProductsDto { Count = u.ProductsSold.Count, Products = u.ProductsSold .OrderByDescending(s => s.Price) .Select(s => new ExportProductDto { Name = s.Name, Price = s.Price }).ToArray() }, }) .ToArray(); var resultObj = new UsersCountDto { Count = usersWithSellsCount.Count(), Users = userSoldProductsDtos }; var serializer = new XmlSerializer(typeof(UsersCountDto), new XmlRootAttribute("Users")); var ns = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) { serializer.Serialize(writer, resultObj, ns); } return(sb.ToString().TrimEnd()); }
public static string GetUsersWithProducts(ProductShopContext context) { var users = context.Users .Where(x => x.ProductsSold.Any()) .OrderByDescending(ps => ps.ProductsSold.Count()) .Select(x => new UsersDto { FirstName = x.FirstName, LastName = x.LastName, Age = x.Age, SoldProducts = new SoldProductsDto { Count = x.ProductsSold.Count(), ProductDtos = x.ProductsSold.Select(ps => new ProductDto { Name = ps.Name, Price = ps.Price }).OrderByDescending(p => p.Price).ToArray() } }) .Take(10) .ToArray(); var usersToPrint = new UsersCountDto { Count = context.Users.Where(x => x.ProductsSold.Any()).Count(), Users = users.ToArray() }; var sb = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(typeof(UsersCountDto), new XmlRootAttribute("Users")); var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", ""), }); serializer.Serialize(new StringWriter(sb), usersToPrint, namespaces); return(sb.ToString().Trim()); }