UnitOfWork と Repository パターンを使用しています。
// 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
}
DBに製品を挿入したいときは、次のようにします:
_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) を変更するにはどうすればよいですか?