2012-03-13 16 views
5

私はlinq to sqlを使用してリポジトリとサービスを作成しましたが、私はそれを理解するのに苦労しました。私はついにそれを理解しましたが、今は同じことをやろうとしていますが、Code First EFを使用しています。私はコードとの最初の動作について混乱しています。クラスオブジェクトに渡してselect()などのリポジトリが1つあれば、これはどうやって相互作用するのでしょうか、これを/ DbContextにどのようにして接続しますか?誰かが正しい方向に私を指すことができるか、または私にいくつかのアドバイスを与えることができればそれは認められるだろう。これはまだ比較的新しいパターンなので、Google上のこのようなものはあまりありません。Entity Frameworkコードを使用してリポジトリを作成する最初の4.3

DbSetを使用する方法は?これらのリポジトリはシンプルですが混乱します。ここ

public class IRepository<T> : IDisposable 
     where T : class, new() 
{ 
    IQueryable<T> Select(); 

    IQueryable<T> SelectWith(params Expression<Func<T, object>>[] includeProperties); 

    T GetById(int id); 

    T GetByIdWith(int id, params Expression<Func<T, object>>[] includeProperties); 

    void InsertOnCommit(T model); 

    void DeleteOnCommit(T model); 

} 


public class DataContext : DbContext 
{ 
} 
+0

は' IRepository 'を実装します。 –

答えて

6

ASP.NetからEFにおけるリポジトリとのUnitOfWorkのTutorialです。この助けを願っています。

public class GenericRepository<TEntity> where TEntity : class 
    { 
     internal SchoolDBContext context; 
     internal DbSet<TEntity> dbSet; 

     public GenericRepository(SchoolDBContext context) 
     { 
      this.context = context; 
      this.dbSet = context.Set<TEntity>(); 
     } 

     public virtual IEnumerable<TEntity> Get( 
      Expression<Func<TEntity, bool>> filter = null, 
      Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, 
      string includeProperties = "") 
     { 
     ... 
     } 

     public virtual TEntity GetByID(object id) 
     { 
      return dbSet.Find(id); 
     } 

     public virtual void Insert(TEntity entity) 
     { 
      dbSet.Add(entity); 
     } 

     ... 
    } 

たUnitOfWork:リポジトリ内のすべての変更内容を更新するには、Save()メソッドを呼び出し

ジェネリックリポジトリたUnitOfWorkは、複数のrepositoresが同じDataContextのを共有することを確認することです)。

public class UnitOfWork : IDisposable 
{ 
    private SchoolDBContext context = new SchoolDBContext(); 
    private GenericRepository<Department> departmentRepository; 

    public GenericRepository<Department> DepartmentRepository 
    { 
     get 
     { 

      if (this.departmentRepository == null) 
      { 
       this.departmentRepository = new GenericRepository<Department>(context); 
      } 
      return departmentRepository; 
     } 
    } 

    public void Save() 
    { 
     context.SaveChanges(); 
    } 
    .... 
} 

コントローラー:あなたがリポジトリに `民間のDataContext context`のようにプライベートフィールドを宣言することができます

public class CourseController : Controller 
{ 
    private UnitOfWork unitOfWork = new UnitOfWork(); 

    // 
    // GET: /Course/ 

    public ViewResult Index() 
    { 
     var courses = unitOfWork.CourseRepository.Get(includeProperties: "Department"); 
     return View(courses.ToList()); 
    } 

    .... 
} 
関連する問題