public static void DeleteCustomer(string customerID) { using (var db = new NorthwindEntities()) { var customer = db.Customers .FirstOrDefault(c => c.CustomerID == customerID); db.Customers.Remove(customer); db.SaveChanges(); } }
public static void ModifyCustomer(string customerID, string contactName, string companyName, string address) { var db = new NorthwindEntities(); using (db) { var customer = db.Customers .FirstOrDefault(c => c.CustomerID == customerID); customer.ContactName = contactName; customer.CompanyName = companyName; customer.Address = address; db.SaveChanges(); } }
public static string InsertCustomer(Customer customer) { if (customer == null) { throw new ArgumentNullException("The customer can't be null"); } else { var db = new NorthwindEntities(); using (db) { db.Customers.Add(customer); db.SaveChanges(); } return customer.CustomerID; } }
static void Main() { //Try to open two different data contexts and perform concurrent changes //on the same records. What will happen at SaveChanges()? - it will going to update //the record two times first to "Ihu" than to "Bla" //How to deal with it? - use only one connection var db1 = new NorthwindEntities(); var db2 = new NorthwindEntities(); Customer customer1 = db1.Customers.FirstOrDefault(c => c.CustomerID == "A"); Customer customer2 = db2.Customers.FirstOrDefault(c => c.CustomerID == "A"); customer1.ContactName = "Ihu"; customer2.ContactName = "Bla"; db1.SaveChanges(); db2.SaveChanges(); }
private static void InsertOrderUsingExternalTransaction(NorthwindEntities db, Order order) { using (db) { using(var transaction = db.Database.BeginTransaction()) { try { db.Orders.Add(order); db.SaveChanges(); transaction.Commit(); } catch (Exception ex) { Console.WriteLine("Can't insert record", ex.Message); transaction.Rollback(); } } } }