Advertisement
Guest User

08. Export Users and Products

a guest
Aug 10th, 2020
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection.PortableExecutable;
  6. using Newtonsoft.Json;
  7. using ProductShop.Data;
  8. using ProductShop.Models;
  9.  
  10. namespace ProductShop
  11. {
  12.     public class StartUp
  13.     {
  14.         public static void Main(string[] args)
  15.         {
  16.             var context = new ProductShopContext();
  17.             //ResetDatabase(context);
  18.             //P08
  19.             var json = GetUsersWithProducts(context);
  20.             File.WriteAllText(@"../../../ExportFiles/users-and-products.json", json);
  21.         }
  22.  
  23.         public static string GetUsersWithProducts(ProductShopContext context)
  24.         {
  25.             var users = context.Users
  26.                 .Where(u => u.ProductsSold.Count > 0)
  27.                 .Select(u => new
  28.                 {
  29.                     firstName = u.FirstName,
  30.                     lastName = u.LastName,
  31.                     age = u.Age,
  32.                     soldProducts = new
  33.                     {
  34.                         count = u.ProductsSold.Count,
  35.                         products = u.ProductsSold
  36.                             .Select(sp => new
  37.                             {
  38.                                 name = sp.Name,
  39.                                 price = sp.Price
  40.                             })
  41.                             .ToArray()
  42.                     }
  43.                 })
  44.                 .OrderByDescending(o => o.soldProducts.count)
  45.                 .ThenBy(o => o.lastName)
  46.                 .ToArray();
  47.  
  48.             var result = new
  49.             {
  50.                 usersCount = users.Count(),
  51.                 users = users
  52.             };
  53.  
  54.             var settings = new JsonSerializerSettings()
  55.             {
  56.                 NullValueHandling = NullValueHandling.Ignore,
  57.                 Formatting = Formatting.Indented
  58.             };
  59.  
  60.  
  61.             var json = JsonConvert.SerializeObject(result, settings);
  62.             return json;
  63.         }
  64.  
  65.         private static void ResetDatabase(ProductShopContext context)
  66.         {
  67.             context.Database.EnsureDeleted();
  68.             Console.WriteLine("Database was successfully deleted.");
  69.  
  70.             context.Database.EnsureCreated();
  71.             Console.WriteLine("Database was successfully created.");
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement