2010-05-12 43 views
1

我正在研究为我正在创建的新ASP.NET MVC项目创建实体框架4通用存储库。我一直在看各种教程,他们似乎都使用工作单元模式... ...实体框架4“工作单元”模式是否适用于通用存储库?

从我一直在阅读,EF使用它已经在ObjectContext中,你只是扩大这个使你自己工作单位。

来源:http://dotnet.dzone.com/news/using-unit-work-pattern-entity?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fdotnet+(.NET+Zone)

一个为什么会去这样做的努力? 这是使用通用存储库的首选方式吗?

非常感谢, Kohan。

回答

3

这不是我使用通用存储库的方式。首先,我会在当前请求中的ClassARepository,CalssBRepository和其他存储库之间共享ObjectContext。使用IOC容器,使用注射和每个请求的行为建议:

这是我的通用仓库什么样子:

public interface IRepository<T> 
{ 
    //Retrieves list of items in table 
    IQueryable<T> List(); 
    IQueryable<T> List(params string[] includes); 
    //Creates from detached item 
    void Create(T item); 
    void Delete(int id); 
    T Get(int id); 
    T Get(int id, params string[] includes); 
    void SaveChanges(); 
} 

public class Repository<T> : IRepository<T> where T : EntityObject 
{ 
    private ObjectContext _ctx; 

    public Repository(ObjectContext ctx) 
    { 
     _ctx = ctx; 
    } 


    private static string EntitySetName 
    { 
     get 
     { 
      return String.Format(@"{0}Set", typeof(T).Name); 
     } 
    } 

    private ObjectQuery<T> ObjectQueryList() 
    { 
     var list = _ctx.CreateQuery<T>(EntitySetName); 
     return list; 
    } 

    #region IRepository<T> Members 

    public IQueryable<T> List() 
    { 
     return ObjectQueryList().OrderBy(@"it.ID").AsQueryable(); 
    } 

    public IQueryable<T> List(params string[] includes) 
    { 
     var list = ObjectQueryList(); 

     foreach(string include in includes) 
     { 
      list = list.Include(include); 
     } 

     return list; 
    } 

    public void Create(T item) 
    { 
     _ctx.AddObject(EntitySetName, item); 
    } 

    public void Delete(int id) 
    { 
     var item = Get(id); 
     _ctx.DeleteObject(item); 
    } 

    public T Get(int id) 
    { 
     var list = ObjectQueryList(); 
     return list.Where("ID = @0", id).First(); 
    } 

    public T Get(int id, params string[] includes) 
    { 
     var list = List(includes); 
     return list.Where("ID = @0", id).First(); 
    } 

    public void SaveChanges() 
    { 
     _ctx.SaveChanges(); 
    } 

    #endregion 

} 

ObjectContext的是通过构造函数注入。 List()方法返回IQueryable,以便在业务层(服务)对象中进一步处理。服务层返回List或IEnumerable,所以视图中不会延迟执行。

此代码是使用EF1创建的。 EF4版本可以有点不同,更简单。

相关问题