使用实体框架的存储库模式

时间:2013-10-23 12:53:40

标签: c# design-patterns entity-framework-4.1 entity-framework-5 repository-pattern

以下是我的代码。我想知道这是不是真的。

public interface IRepository<T> : IDisposable
{
    IQueryable<T> GetAll();
    T Update(T entity);
    T Insert(T entity);
    T GetById(T entity);
    void Delete(T entity);
    void Save();
}

public class Repository<T> : IRepository<T> where T : class
{
    private readonly SchoolDBEntities _context;

    public Repository(SchoolDBEntities context)
    {
        _context = context;
    }

    public IQueryable<T> GetAll()
    {
        return _context.Set<T>();
    }

    public T Update(T entity)
    {
        var result = _context.Set<T>().Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
        return result;
    }

    public T Insert(T entity)
    {
        return _context.Set<T>().Add(entity);
    }

    public T GetById(T entity)
    {
        return _context.Set<T>().Find(entity);
    }

    public void Delete(T entity)
    {
        _context.Set<T>().Remove(entity);
    }

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

    public void Dispose()
    {
        _context.Dispose();
    }
}

问题是,我不知道何时何地调用SaveDispose方法。

3 个答案:

答案 0 :(得分:2)

请勿在{{1​​}}

中进行处置

尝试像这样的UnitOfWork模式

IRepository<T>

你可以这样称呼它

public interface IUnitOfWork : IDisposable
{
    IRepository<Cart> CartRepository { get; }
    IRepository<Product> ProductRepository { get; }
    void Save();
}

public class UnitOfWork : IUnitOfWork
{
    readonly SqlDbContext _context;
    public UnitOfWork()
    {
        _context = new SqlDbContext();
    }

    private bool _disposed;
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

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

    public IGenericRepository<Cart> CartRepository
    {
        get { return new Repository<Cart>(_context); }
    }

    public IGenericRepository<User> UserRepository
    {
        get { return new Repository<User>(_context); }
    }
}

答案 1 :(得分:0)

我认为这取决于你使用这个回购的方式。 因此,当你想要完成你的工作时,你需要保存并处理......在应用程序关闭等等。

答案 2 :(得分:0)

在这里使用Unit of Work模式时,如果用户(存储库)发送save changes命令,显然应该调用Save方法。可能是一个人在您的某个编辑表单或应用程序的其他部分上单击“应用更改”按钮,该按钮处理某些事务逻辑并根据它保存/放弃更改。所以基本上,当准备好保存逻辑变更集时,Repository会处理它。

相关问题