我正在使用 UnitOfWork 和存储库模式。
// generic repository
public class Repository<T> : where T : class
{
private readonly DbSet<T> _dbSet;
public Repository(DbSet<T> dbSet)
{
this._dbSet = dbSet;
}
public IQueryable<T> Queryable()
{
return this._dbSet.AsQueryable();
}
public IEnumerable<T> All()
{
return this._dbSet.AsEnumerable();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
return this._dbSet.Where(where);
}
public T First(Expression<Func<T, bool>> where)
{
return this._dbSet.First(where);
}
public T FirstOrDefault(Expression<Func<T, bool>> where)
{
return this._dbSet.FirstOrDefault(where);
}
public void Add(T entity)
{
this._dbSet.Add(entity);
}
public void Delete(T entity)
{
this._dbSet.Remove(entity);
}
public void Attach(T entity)
{
this._dbSet.Attach(entity);
}
}
// product repository
public class ProductRepository : Repository<Product>
{
public ProductRepository(DbSet<Product> dbSet) : base(dbSet)
{
}
}
// unit of work
public interface IUnitOfWork
{
ProductRepository ProductsRepository { get; }
void Commit();
}
// DbContext as unit of work
public class ApplicationUnitOfWork : DbContext, IUnitOfWork
{
private readonly ProductRepository _productsRepository;
public DbSet<Product> Products { get; set; }
public ApplicationUnitOfWork()
{
_productsRepository = new ProductRepository(Products);
}
#region IUnitOfWork Implementation
public ProductRepository ProductsRepository
{
get { return _productsRepository; }
}
public void Commit()
{
this.SaveChanges();
}
#endregion
}
当我想在数据库中插入产品时,我会这样做:
_unitOfWork.ProductsRepository.Add(new Product());
_unitOfWork.Commit();
这行得通。
我的问题是,如果我在存储库中插入一个产品,然后在调用之前尝试检索它.Commit()
,存储库会返回null
.
Product product = new Product { Id = 5 };
_unitOfWork.ProductsRepository.Add(product);
Product theProduct = _unitOfWork.ProductsRepository.FirstOrDefault(p => p.Id == 5);
// theProduct is null
如何更改存储库模式实现(或 UnitOfWork),使其也返回“内存中”对象?