[英]Repository pattern by using entity framework
以下是我的代码。 我想知道这是真的与否。
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();
}
}
问题是,我不知道何时何地调用Save
和Dispose
方法。
不要在IRepository<T>
进行处理
尝试像这样的UnitOfWork模式
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); }
}
}
你可以这样称呼它
using (_unitOfWork)
{
var p = _unitOfWork.ProductRepository.SingleOrDefault(p => p.Id == productId);
_cartRepository.Add(p);
_unitOfWork.Save();
}
我认为这取决于你使用这个回购的方式。 因此,当你想要完成你的工作时,你需要保存和处理...在应用程序关闭等时...
当您在此处使用工作单元模式时,显然您应该在用户(存储库)发送保存更改命令时调用Save方法。 可能是一个人在您的某个编辑表单或应用程序的其他部分上单击“应用更改”按钮,该按钮处理某些事务逻辑并根据它保存/放弃更改。 所以基本上,当逻辑变更集准备好保存时,Repository会处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.