嗨,我正在尝试首先使用实体框架代码创建一个通用存储库,并将所有内容封装在 UnitOfWork 中,但一定有问题,因为当我尝试添加它并使用我封装的 SaveChanges 时,它不起作用。这是我的存储库代码:
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(entity) 之后添加这一行
Context.SaveChanges()
似乎对象 get 已添加到数据库中。
如何使我的 UnitOfWork SaveChanges 方法起作用?