示例#1
0
        static void Main()
        {
            // 7.Try to open two different data contexts and perform concurrent changes on the same records.
            // What will happen at SaveChanges() ?
            // How to deal with it ?

            using (var northwind1 = new NorthwindEntities())
            {
                using (var northwind2 = new NorthwindEntities())
                {
                    Console.WriteLine(new string('-', 35));
                    Console.WriteLine("First context");
                    Console.WriteLine(new string('-', 35));
                    var person1 = northwind1.Employees.FirstOrDefault();
                    Console.WriteLine("Initial:{0}", person1.FirstName);
                    person1.FirstName = "XAXAXA";
                    Console.WriteLine("Changed:{0}", person1.FirstName);

                    // Change by Entity state Unchanged Modified Detached
                    var dbEntry = northwind1.Entry(person1);
                    dbEntry.State = EntityState.Unchanged;
                    northwind1.SaveChanges();

                    Console.WriteLine(new string('-', 35));
                    Console.WriteLine("Second context");
                    Console.WriteLine(new string('-', 35));
                    var person2 = northwind2.Employees.FirstOrDefault();
                    Console.WriteLine("Initial:{0}", person2.FirstName);
                    person2.FirstName = "UHAHAH";
                    Console.WriteLine("Changed:{0}", person2.FirstName);

                    northwind2.SaveChanges();
                }
            }
        }
示例#2
0
 private static void DeleteCustomer(string customerId)
 {
     using (var northwindEntities = new NorthwindEntities())
     {
         Customer customer = GetCustomerById(northwindEntities, customerId);
         northwindEntities.Customers.Remove(customer);
         northwindEntities.SaveChanges();
     }
 }
示例#3
0
 private static string CreateNewCustomer(string customerId, string companyName, string contactName)
 {
     using (var northwindEntities = new NorthwindEntities())
     {
         Customer newCustomer = new Customer
         {
             CustomerID = customerId,
             CompanyName = companyName,
             ContactName = contactName
         };
         northwindEntities.Customers.Add(newCustomer);
         northwindEntities.SaveChanges();
         return newCustomer.CustomerID;
     }
 }
示例#4
0
 private static void ModifyCustomerName(string customerId, string companyName, string contactName)
 {
     using (var northwindEntities = new NorthwindEntities())
     {
         Customer customer = GetCustomerById(northwindEntities, customerId);
         customer.CompanyName = companyName;
         customer.ContactName = contactName;
         northwindEntities.SaveChanges();
     }
 }