Ejemplo n.º 1
0
        //Problem 08
        public static string GetUsersWithProducts(ProductShopContext context)
        {
            var users = context.Users
                        .ToList()
                        .Where(u => u.ProductsSold.Any(p => p.Buyer != null))
                        .OrderByDescending(u => u.ProductsSold.Count(p => p.Buyer != null))
                        .Select(u => new ExportUserDto()
            {
                FirstName    = u.FirstName,
                LastName     = u.LastName,
                Age          = u.Age,
                SoldProducts = new SoldProductsDto()
                {
                    Count    = u.ProductsSold.Count(p => p.Buyer != null),
                    Products = u.ProductsSold
                               .ToList()
                               .Where(p => p.Buyer != null)
                               .Select(p => new ProductDto()
                    {
                        Name  = p.Name,
                        Price = p.Price
                    })
                               .ToList()
                }
            })
                        //.OrderByDescending(u => u.soldProducts.count)
                        .ToList();

            var resultObj = new UserWithProductsDto()
            {
                Count = users.Count,
                Users = users
            };

            var result = JsonConvert.SerializeObject(resultObj, new JsonSerializerSettings
            {
                Formatting        = Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore
            });

            return(result);
        }
Ejemplo n.º 2
0
        public string ExportSoldProducts()
        {
            var users = context.Users
                        .Include(u => u.ProductsSold)
                        .Where(u => u.ProductsSold.Any())
                        .OrderBy(u => u.LastName)
                        .ThenBy(u => u.FirstName)
                        .ToArray();

            var userDtos = new UserWithProductsDto[users.Length];

            for (var i = 0; i < users.Length; i++)
            {
                var user = users[i];

                var soldProducts = user.ProductsSold
                                   .AsQueryable()
                                   .ProjectTo <SoldProductDto>()
                                   .ToArray();

                userDtos[i] = new UserWithProductsDto
                {
                    FirstName    = user.FirstName,
                    LastName     = user.LastName,
                    SoldProducts = soldProducts
                };
            }

            var sb = new StringBuilder();

            var serializer = new XmlSerializer(userDtos.GetType(), new XmlRootAttribute("users"));

            serializer.Serialize(new StringWriter(sb), userDtos, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));

            return(sb.ToString());
        }