// TODO Problem 08 - Export Users and Products public static string GetUsersWithProducts(ProductShopContext context) { var sb = new StringBuilder(); var users = new UserRootDTO() { Count = context.Users.Count(u => u.FirstName != null), Users = context .Users .Where(u => u.ProductsSold.Count >= 1) .OrderByDescending(u => u.ProductsSold.Count) .Select(u => new UserExportDTO() { FirstName = u.FirstName, LastName = u.LastName, Age = u.Age, SoldProducts = new ProductSoldRootDTO() { Count = u.ProductsSold.Count(ps => ps.Buyer != null), Products = u.ProductsSold .Where(ps => ps.Buyer != null) .Select(s => new ProductSoldDTO() { Name = s.Name, Price = s.Price }) .ToList() } }) .ToList() }; var xmlSerializer = new XmlSerializer(typeof(UserRootDTO), new XmlRootAttribute("Users")); var namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ""); var writer = new StringWriter(sb); using (writer) { xmlSerializer.Serialize(writer, users, namespaces); } return(sb.ToString().Trim()); }
//TODO Problem 08 public static string GetUsersWithProducts(ProductShopContext context) { StringBuilder sb = new StringBuilder(); var namespaces = new XmlSerializerNamespaces(); namespaces.Add(String.Empty, String.Empty); var users = new UserRootDTO() { Count = context.Users.Count(u => u.ProductsSold.Any(p => p.Buyer != null)), Users = context.Users .ToArray() .Where(u => u.ProductsSold.Any(p => p.Buyer != null)) .OrderByDescending(u => u.ProductsSold.Count) .Take(10) .Select(u => new UserExportDTO() { FirstName = u.FirstName, LastName = u.LastName, Age = u.Age, SoldProducts = new SoldProductsDTO() { Count = u.ProductsSold.Count(ps => ps.Buyer != null), Products = u.ProductsSold .ToArray() .Where(ps => ps.Buyer != null) .Select(ps => new ExportProductSoldDTO() { Name = ps.Name, Price = ps.Price }) .OrderByDescending(p => p.Price) .ToArray() } }) .ToArray() }; XmlSerializer xmlSerializer = new XmlSerializer(typeof(UserRootDTO), new XmlRootAttribute("Users")); xmlSerializer.Serialize(new StringWriter(sb), users, namespaces); return(sb.ToString().Trim()); }