Advertisement
Danny_Berova

4.UsersAndProducts.JsonExport

Dec 4th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. static void GetUsersAndProducts()
  2.         {
  3.             using (var db = new ProductsShopContext())
  4.             {
  5.                 var users = db.Users
  6.                     .Where(u => u.ProductsSold.Any(b => b.BuyerId != null))
  7.                     .OrderByDescending(u => u.ProductsSold.Count())
  8.                     .ThenBy(u => u.LastName)
  9.                     .Select(u => new
  10.                     {
  11.                         firstName = u.FirstName,
  12.                         lastName = u.LastName,
  13.                         age = u.Age,
  14.                         soldProducts = new
  15.                         {
  16.                             count = u.ProductsSold.Count(),
  17.                             products = u.ProductsSold.Where(p => p.BuyerId != null)
  18.                             .Select(p => new
  19.                             {
  20.                                 name = p.Name,
  21.                                 price = p.Price
  22.                             })
  23.                         }
  24.                     }).ToArray();
  25.  
  26.                 var usersToJson = new
  27.                 {
  28.                     usersCount = users.Count(),
  29.                     users
  30.                 };
  31.  
  32.                 var jsonString = JsonConvert.SerializeObject(usersToJson, Formatting.Indented,
  33.                     new JsonSerializerSettings()
  34.                     {
  35.                         DefaultValueHandling = DefaultValueHandling.Ignore
  36.                     });
  37.  
  38.  
  39.                 File.WriteAllText("OutputFiles/UsersAndProducts.json", jsonString);
  40.  
  41.             }
  42.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement