嗨我想創建一個通用資源庫,首先使用實體框架代碼,並將所有內容封裝在UnitOfWork中,但一定是錯誤的,因爲當我嘗試添加並使用封裝的SaveChanges時不起作用。 這裏是我的倉庫代碼:保存更改在封裝UnitOFWork類中不起作用
public class Repository<T> : IRepository<T> where T : class
{
private DbContext Context { get; set; }
private DbSet<T> DbSet
{
get { return Context.Set<T>(); }
}
public Repository(DbContext context)
{
Context = context;
}
public virtual IEnumerable<T> GetAll()
{
return DbSet;
}
public virtual T GetById(int id)
{
return DbSet.Find(id);
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = Context.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
public virtual void Update(T entity)
{
DbEntityEntry dbEntityEntry = Context.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(entity);
}
DbSet.Attach(entity);
}
public virtual void Remove(T entity)
{
DbEntityEntry dbEntityEntry = Context.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
public virtual void Remove(int id)
{
var entity = GetById(id);
if (entity == null)
{
return;
}
Remove(entity);
}
}
這裏是我的UnitOfWork代碼:
public class UnitOfWork
{
private readonly RepositoryFactory repositoryFactory;
private DatabaseContext DbContext
{
get { return new DatabaseContext(); }
}
public IRepository<Product> Products
{
get
{
return repositoryFactory.GetRepository<Product>(DbContext);
}
}
public UnitOfWork()
{
repositoryFactory = new RepositoryFactory();
}
public void SavaChanges()
{
DbContext.SaveChanges();
}
}
這是我打電話添加數據和獲取數據的代碼:
var sa = new UnitOfWork();
var repository = sa.Products;;
var result = repository.GetAll();
var resultbyId = repository.GetById(3);
var product = new Product()
{
Name = "sddasd",
CategoryId = 1,
SubcategoryId = 1,
Price = 21,
Description = "dsadasfas",
ImagePath = "Dsadas",
NumberOfProducts = 29
};
repository.Add(product);
sa.SavaChanges()
後運行這段代碼似乎出於某種原因,我在我的UnitOfWork類中封裝的SaveChanges不起作用。
但是,如果如我之後DbSet.Add(實體)加入這一行
Context.SaveChanges()
看來,對象獲取的添加到數據庫中。
如何使我的UnitOfWork SaveChanges方法正常工作?
如何在存儲庫上實現IDisposable,並重用EF內置的工作單元? –