private static void InsertTrip() { var trip = new CodeFirst.Model.Trip { CostUSD = 800, StartDate = new DateTime(2011, 9, 1), EndDate = new DateTime(2011, 9, 14) }; using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { context.Trips.Add(trip); context.SaveChanges(); } }
private static void InsertPerson() { var person = new CodeFirst.Model.Person { FirstName = "Rowan", LastName = "Miller", SocialSecurityNumber = 12345678 }; using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { context.People.Add(person); context.SaveChanges(); } }
private static void InsertDestination() { var destination = new CodeFirst.Model.Destination { Country = "Indonesia", Description = "EcoTourism at its best in exquisite Bali", Name = "Bali" }; using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { context.Destinations.Add(destination); context.SaveChanges(); } }
private static void UpdatePerson() { using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { var person = context.People.FirstOrDefault(); person.FirstName = "Rowena"; context.SaveChanges(); } }
//并发控制的试验: private static void UpdateTrip2() { var firstContext = new CodeFirst.DataAccess.BreakAwayContext(); var trip1 = firstContext.Trips.FirstOrDefault(); //第一个用户取出第一条记录 trip1.CostUSD = 750; //修改但是还没来得及保存 using (var secondContext = new CodeFirst.DataAccess.BreakAwayContext()) { var trip2 = secondContext.Trips.FirstOrDefault(); //第二个用户进来同样取出第一条记录 trip2.CostUSD = 900; secondContext.SaveChanges(); //修改并保存(保存的操作不仅修改了CostUSD为900,同时修改了RowVersion) } try { firstContext.SaveChanges(); //此时第一个用户想保存,但是RowVersion已经改变了 Console.WriteLine("保存成功!"); } catch (DbUpdateConcurrencyException ex) { Console.WriteLine(ex.Entries.First().Entity.GetType().Name + " 保存失败"); } finally { firstContext.Dispose(); } }
private static void UpdateTrip() { using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { var trip = context.Trips.FirstOrDefault(); Console.WriteLine(ToHexString(trip.RowVersion)); //输出修改前的时间戳值 trip.CostUSD = 750; context.SaveChanges(); var trips = context.Trips.FirstOrDefault(); Console.WriteLine(ToHexString(trip.RowVersion)); //输出修改后的时间戳值 } }