1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //DbContext context = ContextFactory.GetContext(); 6 //OrderInfo oi = new OrderInfo() 7 //{ 8 // OrderTitle="三星手机" 9 //}; 10 //oi.CustomerInfo = new CustomerInfo() 11 //{ 12 // CustomerName="淳于琼", 13 // CustomerDate=DateTime.Now 14 //}; 15 //context.Set<OrderInfo>().Add(oi); 16 //context.SaveChanges(); 17 //Console.WriteLine("OK"); 18 //Console.ReadKey(); 19 20 //测试, 21 AddCustomerInfo(); 22 AddOrderInfo(); 23 Save(); 24 Console.WriteLine("OK"); 25 Console.ReadKey(); 26 27 } 28 /// <summary> 29 /// 30 /// </summary> 31 private static void Save() 32 { 33 DbContext context = ContextFactory.GetContext(); 34 context.SaveChanges(); 35 } 36 37 private static void AddCustomerInfo() 38 { 39 DbContext context = ContextFactory.GetContext(); 40 context.Set<CustomerInfo>().Add(new CustomerInfo() 41 { 42 CustomerName = "大张伟", 43 CustomerDate = DateTime.Now 44 }); 45 46 } 47 48 private static void AddOrderInfo() 49 { 50 DbContext context = ContextFactory.GetContext(); 51 context.Set<OrderInfo>().Add(new OrderInfo() 52 { 53 OrderTitle="七星宝刀", 54 CustomerId=7 55 }); 56 } 57 } 58 /// <summary> 59 /// 获取上下文对象的类 60 /// </summary> 61 public static class ContextFactory 62 { 63 public static DbContext GetContext() 64 { 65 //从数据槽中获取上下文对象,保证对象的单一 66 DbContext context = CallContext.GetData("DbContext") as DbContext; 67 if (context == null) 68 { 69 //当数据槽中不存在的时候。创建一个上下文对象并把它放在数据槽中 70 context = new EFTestEntities(); 71 CallContext.SetData("DbContext", context); 72 } 73 return context; 74 } 75 }
时间: 2024-12-18 17:25:45