0

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) を変更するにはどうすればよいですか?

4

1 に答える 1

0

オプション1

Findではなくメソッドを使用してくださいFirstOrDefaultこの記事を見て、それがどのように機能するかを確認してください。

DbSet の Find メソッドは、主キーの値を使用して、コンテキストによって追跡されるエンティティを見つけようとします。コンテキスト内でエンティティが見つからない場合は、クエリがデータベースに送信され、そこでエンティティが検索されます。コンテキストまたはデータベースでエンティティが見つからない場合は、null が返されます。検索は、次の 2 つの重要な点でクエリの使用とは異なります。指定されたキーを持つエンティティがコンテキストで見つからない場合にのみ、データベースへのラウンドトリップが行われます。Find は、Added 状態のエンティティを返します。

オプション#2

ローカル データをクエリします。この記事をご覧ください。

于 2013-06-20T09:13:25.050 に答える