Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection.PortableExecutable;
- using Newtonsoft.Json;
- using ProductShop.Data;
- using ProductShop.Models;
- namespace ProductShop
- {
- public class StartUp
- {
- public static void Main(string[] args)
- {
- var context = new ProductShopContext();
- //ResetDatabase(context);
- //P08
- var json = GetUsersWithProducts(context);
- File.WriteAllText(@"../../../ExportFiles/users-and-products.json", json);
- }
- public static string GetUsersWithProducts(ProductShopContext context)
- {
- var users = context.Users
- .Where(u => u.ProductsSold.Count > 0)
- .Select(u => new
- {
- firstName = u.FirstName,
- lastName = u.LastName,
- age = u.Age,
- soldProducts = new
- {
- count = u.ProductsSold.Count,
- products = u.ProductsSold
- .Select(sp => new
- {
- name = sp.Name,
- price = sp.Price
- })
- .ToArray()
- }
- })
- .OrderByDescending(o => o.soldProducts.count)
- .ThenBy(o => o.lastName)
- .ToArray();
- var result = new
- {
- usersCount = users.Count(),
- users = users
- };
- var settings = new JsonSerializerSettings()
- {
- NullValueHandling = NullValueHandling.Ignore,
- Formatting = Formatting.Indented
- };
- var json = JsonConvert.SerializeObject(result, settings);
- return json;
- }
- private static void ResetDatabase(ProductShopContext context)
- {
- context.Database.EnsureDeleted();
- Console.WriteLine("Database was successfully deleted.");
- context.Database.EnsureCreated();
- Console.WriteLine("Database was successfully created.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement