using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using HeuristicLab.Services.Optimization.Billing.Model; namespace HeuristicLab.Services.Optimization.Billing.DataAccess { public class BillingDao { #region Context Creation and Execution private BillingContext CreateContext() { BillingContext context = new BillingContext("name=BillingContext"); return context; } private delegate T ExecuteWithContextDelegate(BillingContext context); private delegate void ExecuteWithContextDelegate(BillingContext context); private void ExecuteWithContext(ExecuteWithContextDelegate call) { BillingContext context = null; try { using (context = CreateContext()) { call(context); } } finally { if (context.Database.Connection.State == System.Data.ConnectionState.Open) { context.Database.Connection.Close(); } } } private T ExecuteWithContext(ExecuteWithContextDelegate call) { BillingContext context = null; try { using (context = CreateContext()) { T result = call(context); return result; } } finally { if (context.Database.Connection.State == System.Data.ConnectionState.Open) { context.Database.Connection.Close(); } } } #endregion #region Product Methods public Product FindProductById(long id) { return ExecuteWithContext((context) => { return context.Products.FirstOrDefault(prod => prod.ProductId == id); }); } public IEnumerable FindProdcutBy(Expression> predicate) { using (var context = CreateContext()) { var products = context.Products.Where(predicate).ToList(); return products; } } public IEnumerable FindAllProducts() { using (var context = CreateContext()) { var products = context.Products.ToList(); return products; } } public void AddProduct(Product entity) { ExecuteWithContext((context) => { context.Products.Add(entity); context.SaveChanges(); }); } public void UpdateProduct(Product entity) { ExecuteWithContext((context) => { context.Products.Attach(entity); context.Entry(entity).State = System.Data.EntityState.Modified; context.SaveChanges(); }); } void DeleteProduct(Product entity) { ExecuteWithContext((context) => { context.Products.Remove(entity); }); } #endregion #region Order Methods public void AddOrder(Order order) { ExecuteWithContext((context) => { context.Orders.Add(order); context.SaveChanges(); }); } public IEnumerable FindOrderBy(Expression> predicate) { using (var context = CreateContext()) { var orders = context.Orders.Where(predicate).ToList(); return orders; } } #endregion } }