// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; namespace Order.Backend { public class MyDbContext : DbContext { public MyDbContext() : base("devproc") { Database.Log = Console.Write; } public DbSet Customers { get; set; } public DbSet Products { get; set; } public DbSet Orders { get; set; } public DbSet OrderLines { get; set; } } public class Stats { public string Name { get; set; } public int NOrders { get; set; } public decimal TotSale { get; set; } } public class Persister { public int GetNextCustomerId() { using(MyDbContext db = new MyDbContext()) { return db.Customers.Select(c => c.Id).Max() + 1; } } public int GetNextOrderId() { using(MyDbContext db = new MyDbContext()) { return db.Orders.Select(o => o.Id).Max() + 1; } } public int GetNextOrderLineId() { using(MyDbContext db = new MyDbContext()) { return db.OrderLines.Select(ol => ol.Id).Max() + 1; } } public IList GetCustomers() { using(MyDbContext db = new MyDbContext()) { return db.Customers.ToList(); } } public IList GetProducts() { using(MyDbContext db = new MyDbContext()) { return db.Products.ToList(); } } public void SaveCustomer(Customer c) { using(MyDbContext db = new MyDbContext()) { db.Customers.Add(c); db.SaveChanges(); } } public void SaveOrder(Order o) { using(MyDbContext db = new MyDbContext()) { db.Orders.Add(o); db.SaveChanges(); } } public Order LookupOrder(int orderid) { using(MyDbContext db = new MyDbContext()) { return db.Orders.Include(o => o.Customer).Include(o => o.Lines).Include(o => o.Lines.Select(ol => ol.Product)).Where(o => o.Id == orderid).FirstOrDefault(); } } public IList GetSalesStats() { using(MyDbContext db = new MyDbContext()) { // this query is not ORM and LINQ friendly so it is done in SQL instead IDbConnection con = db.Database.Connection; con.Open(); IDbCommand q = con.CreateCommand(); q.Connection = con; q.CommandText = "SELECT customers.name AS name,COUNT(DISTINCT orders.id) AS norders,SUM(orderlines.quantity*products.price) AS totsale " + "FROM ((customers LEFT JOIN orders ON customers.id = orders.customerid) " + " JOIN orderlines ON orders.id = orderlines.orderid) " + " JOIN products ON orderlines.productid = products.id " + "GROUP BY customers.name"; IDataReader rdr = q.ExecuteReader(); IList result = new List(); while(rdr.Read()) { result.Add(new Stats { Name = (string)rdr["name"], NOrders = (int)rdr["norders"], TotSale = (decimal)rdr["totsale"] }); } return result; } } } }