Asp.net mvc DbContext—存储库和工作单元模式的组合?

Asp.net mvc DbContext—存储库和工作单元模式的组合?,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,不知道我能不能在这里得到一些指导。在DbContext的MSDN页面()上,它指出:“表示工作单元和存储库模式的组合,使您能够查询数据库并将更改分组,然后将这些更改作为一个单元写回存储。” 我对存储库模式的理解是,它提供了对数据持久性层的抽象。如何将耦合到EF的具体实现视为抽象 另外,我将如何利用它作为工作模式的一个单元?目前,我的工作单元有一个ObjectContext属性,我的每个repo都有一个属性: public class UnitOfWork : IUnitOfWork {

不知道我能不能在这里得到一些指导。在DbContext的MSDN页面()上,它指出:“表示工作单元和存储库模式的组合,使您能够查询数据库并将更改分组,然后将这些更改作为一个单元写回存储。”

我对存储库模式的理解是,它提供了对数据持久性层的抽象。如何将耦合到EF的具体实现视为抽象

另外,我将如何利用它作为工作模式的一个单元?目前,我的工作单元有一个ObjectContext属性,我的每个repo都有一个属性:

public class UnitOfWork : IUnitOfWork
{
    private TPSEntities _context = new TPSEntities();
    private ICustomerRepository _customerRepository;
    private IUsersRepository _UsersRepository;

    public ICustomerRepository CustomerRepository
    {
        get
        {
            if (_customerRepository == null)
            {
                _customerRepository = new CustomerRepository(_context);
            }
            return _customerRepository;
        }
    }

    public IUsersRepository UsersRepository
    {
        get
        {
            if (_UsersRepository == null)
            {
                _UsersRepository = new UsersRepository(_context);
            }
            return _UsersRepository;
        }
    }


    public void Save()
    {
        _context.SaveChanges();
    }

    public void Save(string storedProcedure)
    {
        _context.SaveChanges();
        //_context.ExecuteStoreCommand
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
然后,我通过DI将我的工作单元对象注入到我的控制器中,然后离开

使用DbContext有更好的方法吗

谢谢


Chris

事实上,
DbContext
是对数据库的一种抽象-微软的几种SQL引擎都可以使用EF,如果您在代码中使用EF,那么在引擎之间切换只需更改connectionstring

这就是说,在您的案例中,希望通过ORM工具-EF实现另一个抽象并不罕见。我发现大多数指南、博客文章等都通过抽象ORM工具来演示存储库模式。你也是,在你提供的代码中


我想这可以归结为您对“数据库层”和“存储库”的定义——尽管我确信文献中有严格的定义,但这些定义在互联网上并不一致。(惊讶?:P)

ObjectContext或DbContext在逻辑上没有任何区别。