static void Main(string[] args) { BinaryFormatter binarySerializer = new BinaryFormatter(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(List <Category>)); Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer(); using (var db = new DbNorthwind()) { // Eager loading List <Category> categories = db.Categories.Include(c => c.Products).ToList(); using (FileStream file = File.Create("CategoriesAndProducts.dat")) { binarySerializer.Serialize(file, categories); } using (FileStream file = File.Create("CategoriesAndProducts.xml")) { xmlSerializer.Serialize(file, categories); } using (StreamWriter file = File.CreateText(Combine(CurrentDirectory, "CategoriesAndProducts.json"))) { jsonSerializer.Serialize(file, categories); } } // Deserialed all formats to check using (FileStream file = File.Open("CategoriesAndProducts.xml", FileMode.Open)){ var cats = xmlSerializer.Deserialize(file) as List <Category>; foreach (var cat in cats) { WriteLine($"Category ID {cat.CategoryID}, category Name {cat.CategoryName}, {cat.Products.Count}"); } } using (FileStream file = File.Open("CategoriesAndProducts.dat", FileMode.Open)){ var cats = binarySerializer.Deserialize(file) as List <Category>; foreach (var cat in cats) { WriteLine($"Category ID {cat.CategoryID}, category Name {cat.CategoryName}, {cat.Products.Count}"); } } using (StreamReader file = File.OpenText("CategoriesAndProducts.json")) { var cats = jsonSerializer.Deserialize(file, typeof(List <Category>)) as List <Category>; foreach (var cat in cats) { WriteLine($"Category ID {cat.CategoryID}, category Name {cat.CategoryName}, {cat.Products.Count}"); } } }
static void PrintCustomersCompanyByCity(string city) { using (var db = new DbNorthwind()){ var queryCustomerName = from customer in db.Customers where customer.City == city orderby customer.City select customer.CompanyName; queryCustomerName.Distinct(); WriteLine("There are {0} customers in {1}:", queryCustomerName.Count(), city); foreach (var company in queryCustomerName) { WriteLine(company); } } }
static void PrintUniqueCustomerCities() { using (var db = new DbNorthwind()){ var queryCities = db.Customers .OrderBy(customer => customer.City) .Select(customer => customer.City) .Distinct().ToArray(); int NumberOfCities = queryCities.Count(); WriteLine("Available {0} cities:", NumberOfCities); for (int i = 0; i < NumberOfCities; i++) { if (i != NumberOfCities - 1) { Write("{0}, ", queryCities[i]); } else { WriteLine("{0} ", queryCities[i]); } } } }