Entity Framework Context上下文管理(CallContext 数据槽)

Context上下文管理

Q1:脏数据

Q2:一次逻辑操作中,会多次访问数据库,增加了数据库服务器的压力

>在一次逻辑操作中实现上下文实例唯一

方法一:单例模式:内存的爆炸式增长

    在整个运行期间是静态的,保持加载对象不会被回收,所有跟踪的对象也都不会被回收

方式二:CallContext(线程数据槽):

    1:线程独享的数据槽。2:集合结构 (web也可以使用HttpContext)

CallContext 类 (System.Runtime.Remoting.Messaging)_files 链接: http://pan.baidu.com/s/1c2LRbmo  密码: 52zp

对比使用EF与ADO.NET

优点:开发简单快捷,强大的模型设计,跨数据库支持

缺点:效率低(把EF操作转换为SQL语句)

1:使用EntityFramework Database First方式创建CustomerInfo表格数据映射

Entity Framework(EF的Database First方法) :http://www.cnblogs.com/Dr-Hao/p/5367147.html

2:新建ContextFactory.cs封装工厂类

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace CallContextTest
{
    public class CallContextFactory
    {
        public static DbContext GetContext()
        {
            //通过CallContext数据槽,可以实现线程类实例唯一的功能
            DbContext context = CallContext.GetData("context") as DbContext;
            if (context==null)
            {
                context = new MyFirstEFEntities();
                CallContext.SetData("context",context);
            }
            //每次都新建上下文对象,在一次逻辑操作中,无法保证数据的正确性
            //DbContext context = new MyFirstEFEntities();
            return context;
        }
    }
}

3:Program.cs 程序中的测试代码

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CallContextTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            test1.Add();
            Test2 test2 = new Test2();
            test2.Add();

            DbContext context = CallContextFactory.GetContext();
            var item = context.Set<CustomerInfo>().Find(1);
            Console.WriteLine(item.customerName);

            Console.ReadKey();
        }
    }

    public class Test1
    {
        public void Add()
        {
            DbContext context = CallContextFactory.GetContext();
            var item = context.Set<CustomerInfo>().Find(1);
            item.customerName += "1";
        }
    }

    public class Test2
    {
        public void Add()
        {
            DbContext context = CallContextFactory.GetContext();
            var item = context.Set<CustomerInfo>().Find(1);
            item.customerName += "2";
        }
    }
}

最后输出结果为 item.customerName+"12"; 这样在一次逻辑操作中,通过CallContext数据槽,可以实现线程类实例唯一的功能,保证数据的正确性。

posted @ 2016-04-22 13:45  DrHao  阅读(2314)  评论(5编辑  收藏  举报