【问题标题】:Thread Safe Unit of Work with EntityFramework使用 EntityFramework 的线程安全工作单元
【发布时间】:2013-09-17 00:12:43
【问题描述】:

我有一个数据层,它使用一个工作单元,它基本上是 EnityFramework 数据上下文的包装器。

随着所有异步等待的事情发生,我想我会开始尝试通过一些异步调用来使用这个数据层。 (我一般是异步编程的新手)

我很快就遇到了“已经有一个与此命令关联的开放数据读取器”错误的问题。

有没有让我的工作单元线程安全的好方法?或者我应该在我即将拨打电话时创建它的另一个实例(换句话说......要更加小心)。

是否有任何好的资源可以检查这样做?

我的几次谷歌搜索并没有太多,所以我想我会提出这个问题。

我的 Uow 看起来像这样。

public class MyUnitOfWork: IMyUnitOfWork, IDisposable
{
    private MyDbContext DbContext { get; set; }
    protected IRepositoryProvider RepositoryProvider;

    public MyUnitOfWork(IRepositoryProvider repositoryProvider)
    {
        CreateDbContext();


        repositoryProvider.DbContext = DbContext;
        RepositoryProvider = repositoryProvider;
    }

    public MyUnitOfWork(IRepositoryProvider repositoryProvider, MyDbContext context)
    {
        DbContext = context;

        repositoryProvider.DbContext = DbContext;
        RepositoryProvider = repositoryProvider;

    }
    public void CreateDbContext()
    {
        DbContext = new MyDbContext();

        //Serialization false if we enable proxied entities
        DbContext.Configuration.ProxyCreationEnabled = false;

        //avoid serilaization trouble
        DbContext.Configuration.LazyLoadingEnabled = false;
    }
    public void Commit()
    {
        DbContext.SaveChanges();
    }

    public IRepository<Person> Persons {get { return repositoryProvider.GetRepo<Person>(); } }

    public IRepository<SomeOtherEntityType> SomeOtherType {get { return repositoryProvider.GetRepo<SomeOtherEntityType>(); } }

    // IDisposable 
    // ...
}

【问题讨论】:

  • 实体框架对于开始使用async/await 来说可能是一个糟糕的选择,因为它的上下文不是线程安全的。为了使其线程安全,您最好将上下文包装在序列化数据库调用的东西中,这可能会适得其反。
  • @StephenCleary 不,这是 EF5,尽管如果它为我提供了我需要的东西,我可以切换到 EF6,而不会有太多麻烦。这还没有在任何生产代码或任何东西中使用。
  • EF6 是第一个支持async 的版本。

标签: c# entity-framework asynchronous unit-of-work


【解决方案1】:

本文提供了有关如何使用 DbContext、生命周期、多线程等方面的一般指南。

http://msdn.microsoft.com/en-us/data/jj729737.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 2011-05-06
    • 1970-01-01
    • 2012-03-18
    • 2011-03-30
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多