代码之家  ›  专栏  ›  技术社区  ›  4imble

实体框架4“工作单元”模式是通用存储库的发展方向吗?

  •  1
  • 4imble  · 技术社区  · 16 年前

    我正在研究为一个新的ASP.NETMVC项目创建EntityFramework4通用存储库。我一直在看各种教程,他们似乎都使用单位工作模式。。。

    从我读到的内容来看,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)

    为什么一个人要去努力做到这一点? 这是使用通用存储库的首选方法吗?

    非常感谢, 科汉。

    1 回复  |  直到 16 年前
        1
  •  3
  •   LukLed    16 年前

    这不是我处理泛型存储库的方式。首先,我将在当前请求中的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
    
    }
    

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

    推荐文章