码迷,mamicode.com
首页 > 其他好文 > 详细

15----EFContext对象从数据槽获取---单例模式

时间:2016-04-28 16:55:36      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:

 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     }

 

15----EFContext对象从数据槽获取---单例模式

标签:

原文地址:http://www.cnblogs.com/clcloveHuahua/p/5443054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!