public static string GetUsersWithProducts(ProductShopContext context) { StringBuilder sb = new StringBuilder(); var users = new UsersRootDto() { 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 UserOutputModelDto() { FirstName = u.FirstName, LastName = u.LastName, Age = u.Age, SoldProducts = new SoldProductDto() { Count = u.ProductsSold.Count(ps => ps.Buyer != null), Products = u.ProductsSold .ToArray() .Where(ps => ps.Buyer != null) .Select(ps => new ProductOutputModelDto() { Name = ps.Name, Price = ps.Price }) .OrderByDescending(p => p.Price) .ToArray() } }) .ToArray() }; var xmlSerializer = new XmlSerializer(typeof(UsersRootDto), new XmlRootAttribute("Users")); var stringWriter = new StringWriter(); var ns = new XmlSerializerNamespaces(); ns.Add("", ""); xmlSerializer.Serialize(stringWriter, users, ns); return(stringWriter.ToString()); }
public static string GetUsersWithProducts(ProductShopContext context) { var user = new UsersRootDto() { Count = context.Users.Count(x => x.ProductsSold.Any(a => a.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 UserDto() { FirstName = u.FirstName, LastName = u.LastName, Age = u.Age.Value, SoldProducts = new SoldProductsDto { Count = u.ProductsSold.Count(ps => ps.Buyer != null), Products = u.ProductsSold .ToArray() .Where(ps => ps.Buyer != null) .Select(ps => new ProductsDto() { Name = ps.Name, Price = ps.Price }) .OrderByDescending(p => p.Price) .ToArray() } }) .ToArray() }; var result = XmlConverter.Serialize(user, "Users"); return(result); }