Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 什么';s使用实体框架、存储库和UnitOfWork模式的数据服务最佳实践_Entity Framework_Repository_Data Access Layer_Unit Of Work_Dataservice - Fatal编程技术网

Entity framework 什么';s使用实体框架、存储库和UnitOfWork模式的数据服务最佳实践

Entity framework 什么';s使用实体框架、存储库和UnitOfWork模式的数据服务最佳实践,entity-framework,repository,data-access-layer,unit-of-work,dataservice,Entity Framework,Repository,Data Access Layer,Unit Of Work,Dataservice,我正在使用EF和MVVM模式。我的问题是关于数据访问层。在DAL中,我有以下课程: MyObjectContext从技术上讲,它现在是标准的ObjectContext,但稍后将添加一些工作单元方法 存储库处理不同对象集上最需要的查询(如Add、GetAll等) 一组数据服务,它们利用存储库为Core提供更高级别的数据访问 我正在开发的项目是一个业务应用程序,到目前为止大约有100个EntitySet,有时一个用户的一次交互最多可以涉及20个不同的EntitySet(更新其中的大部分)。我目前将.

我正在使用EF和MVVM模式。我的问题是关于数据访问层。在DAL中,我有以下课程:

  • MyObjectContext
    从技术上讲,它现在是标准的ObjectContext,但稍后将添加一些工作单元方法

  • 存储库
    处理不同对象集上最需要的查询(如Add、GetAll等)

  • 一组
    数据服务
    ,它们利用存储库为Core提供更高级别的数据访问

  • 我正在开发的项目是一个业务应用程序,到目前为止大约有100个EntitySet,有时一个用户的一次交互最多可以涉及20个不同的EntitySet(更新其中的大部分)。我目前将
    .Include(params string[])
    添加到我的查询中,以防止
    ObjectContextDisposedException
    ,但这似乎不是一个可靠的解决方案

    问题是我是否应该在每个DataService方法中创建一个
    MyObjectContext
    (并因此创建存储库)的实例(就像下面的代码一样,在这种情况下,工作单元的能力似乎是无用的)或者我应该在DataService之外创建它,并通过它们的构造函数(或直接传递给每个DataService方法)将它传递给DataService,以便一起处理一系列数据库操作(不同的表和查询)。怎么做

    以下是
    MyObjectContext
    的外观:

    public class MyObjectContext : ObjectContext, IUnitOfWork
    {
        public MyObjectContext()
            : base("name=EdmContainer", "EdmContainer")
        {
            ContextOptions.LazyLoadingEnabled = true;
        }
    
        #region IUnitOfWork Members
        public void Commit()
        {
            SaveChanges();
        }
        #endregion
    }
    
    public class Repository<TModel>
    {
        private readonly SoheilEdmContext _context;
    
        public Repository(IUnitOfWork unitOfWork)
        {
            if (unitOfWork == null)
                throw new ArgumentNullException("unitOfWork");
    
            _context = unitOfWork as SoheilEdmContext;
        }
        public TModel FirstOrDefault(Expression<Func<TModel, bool>> where)
        {
            return _context.CreateObjectSet<TModel>().FirstOrDefault(where);
        }
        public void Add(TModel entity)
        {
            _context.CreateObjectSet<TModel>().AddObject(entity);
        }
        ...
    }
    
    public class JobDataService : IDataService<Job>
    {
        #region IDataService<Job> Members
        public Job GetSingle(int id)
        {
            Job model = null;
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                model = repos.FirstOrDefault(x => x.Id == id);
            }
            return model;
        }
    
        public IEnumerable<Job> GetAll()
        {
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                var models = repos.GetAll();
                return models;
            }
        }
    
        public IEnumerable<Job> GetActives()
        {
            throw new NotImplementedException();
        }
    
        public int AddModel(Job model)
        {
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                repos.Add(model);
                context.SaveChanges();
            }
        }
    
        public void UpdateModel(Job model)
        {
            throw new NotImplementedException();
        }
    
        public void DeleteModel(Job model)
        {
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                var model = repos.FirstOrDefault(x => x.Id == model.Id);
                if (model == null) return;
                repos.Delete(model);
                context.SaveChanges();
            }
        }
        #endregion
    }
    
    这就是
    存储库
    的样子:

    public class MyObjectContext : ObjectContext, IUnitOfWork
    {
        public MyObjectContext()
            : base("name=EdmContainer", "EdmContainer")
        {
            ContextOptions.LazyLoadingEnabled = true;
        }
    
        #region IUnitOfWork Members
        public void Commit()
        {
            SaveChanges();
        }
        #endregion
    }
    
    public class Repository<TModel>
    {
        private readonly SoheilEdmContext _context;
    
        public Repository(IUnitOfWork unitOfWork)
        {
            if (unitOfWork == null)
                throw new ArgumentNullException("unitOfWork");
    
            _context = unitOfWork as SoheilEdmContext;
        }
        public TModel FirstOrDefault(Expression<Func<TModel, bool>> where)
        {
            return _context.CreateObjectSet<TModel>().FirstOrDefault(where);
        }
        public void Add(TModel entity)
        {
            _context.CreateObjectSet<TModel>().AddObject(entity);
        }
        ...
    }
    
    public class JobDataService : IDataService<Job>
    {
        #region IDataService<Job> Members
        public Job GetSingle(int id)
        {
            Job model = null;
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                model = repos.FirstOrDefault(x => x.Id == id);
            }
            return model;
        }
    
        public IEnumerable<Job> GetAll()
        {
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                var models = repos.GetAll();
                return models;
            }
        }
    
        public IEnumerable<Job> GetActives()
        {
            throw new NotImplementedException();
        }
    
        public int AddModel(Job model)
        {
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                repos.Add(model);
                context.SaveChanges();
            }
        }
    
        public void UpdateModel(Job model)
        {
            throw new NotImplementedException();
        }
    
        public void DeleteModel(Job model)
        {
            using (var context = new MyObjectContext())
            {
                var repos = new Repository<Job>(context);
                var model = repos.FirstOrDefault(x => x.Id == model.Id);
                if (model == null) return;
                repos.Delete(model);
                context.SaveChanges();
            }
        }
        #endregion
    }
    

    任何想法或见解都将不胜感激。

    您可以在每个服务(如JobDataService)中创建MyObjectContext的实例,但是,它会使您的代码凌乱且难以维护。在DataService之外创建MyObjectContext实例更好。现在,如果有100个EntitySet,就必须创建100个数据服务。这是因为在这里使用“存储库模式”和“UnitOfWork”效率不高。我建议采取以下措施:

    ObjectContext

    public class MyObjectContext : ObjectContext
    {
        public MyObjectContext() : base("name=EdmContainer", "EdmContainer")
        {
            ContextOptions.LazyLoadingEnabled = true;
        }
    
        #region IUnitOfWork Members
        public void Commit()
        {
            SaveChanges();
        }
        #endregion
    }
    
    通用存储库

     public interface IRepository<TModel> where TModel : class
        {
            void Add(TModel entity);
            IEnumerable<TModel> GetAll();
            // Do some more implement
        }
    
    
        public class Repository<TModel> : IRepository<TModel> where TModel : class
        {
            private readonly ObjectContext _context;
    
            public Repository(ObjectContext context)
            {
                _context = context;
            }
    
            public virtual void Add(TModel entity)
            {
                _context.CreateObjectSet<TModel>().AddObject(entity);
            }
    
            public virtual IEnumerable<TModel> GetAll()
            {
                return _context.CreateObjectSet<TModel>();
            }
        }
    
    公共接口IRepository,其中TModel:class
    {
    无效添加(TModel实体);
    IEnumerable GetAll();
    //多做一些练习
    }
    公共类存储库:IRepository,其中TModel:class
    {
    私有只读ObjectContext\u上下文;
    公共存储库(ObjectContext上下文)
    {
    _上下文=上下文;
    }
    公共虚拟空添加(TModel实体)
    {
    _context.CreateObjectSet().AddObject(实体);
    }
    公共虚拟IEnumerable GetAll()
    {
    返回_context.CreateObjectSet();
    }
    }
    
    工作单元

    public interface IUnitOfWork : IDisposable
    {
        IRepository<Job> Jobs { get; }
        IRepository<User> Users { get;} 
        void Commit();
    }
    
        public class UnitOfWork : IUnitOfWork
        {
            private readonly SoheilEdmContext _context;
            private readonly IRepository<Job> _jobRepository;
            private readonly IRepository<User> _userRepository; 
    
            public UnitOfWork(SoheilEdmContext context)
            {
                _context = context;
                _jobRepository = new Repository<Job>(_context);
                _userRepository = new Repository<User>(_context);
            }
            public IRepository<Job> Jobs{get { return _jobRepository; }}
            public IRepository<User> Users{get { return _userRepository; }}
            public void Commit(){_context.Commit();}
            public void Dispose()
            {
                if (_context != null)
                {
                    _context.Dispose();
                }
    
                GC.SuppressFinalize(this);
            }
    
    公共接口IUnitOfWork:IDisposable
    {
    i假定作业{get;}
    IRepository用户{get;}
    无效提交();
    }
    公共类UnitOfWork:IUnitOfWork
    {
    私有只读SoheiledMcContext\u上下文;
    私有只读IRepository\u作业存储库;
    私有只读IRepository用户存储库;
    公共工作单元(SoheiledMcContext上下文)
    {
    _上下文=上下文;
    _jobRepository=新存储库(_上下文);
    _userRepository=新存储库(_上下文);
    }
    公共IRepository作业{get{return}jobRepository;}
    公共IRepository用户{get{return}userRepository;}
    public void Commit(){u context.Commit();}
    公共空间处置()
    {
    如果(_context!=null)
    {
    _context.Dispose();
    }
    总干事(本);
    }
    
    JodDataSerivce

    public interface IDataService
            {
                IEnumerable<Job> GetAll();
            }
    
            public class DataService : IDataService
            {
                private readonly IUnitOfWork _unitOfWork;
                public DataService(IUnitOfWork unitOfWork)
                {
                    _unitOfWork = unitOfWork;
                }
    
                public IEnumerable<Job> GetAll()
                {
                    return _unitOfWork.Jobs.GetAll();
                }
            }
    
    公共接口IDataService
    {
    IEnumerable GetAll();
    }
    公共类数据服务:IDataService
    {
    私人只读i工作单元(unitof工作单元);;
    公共数据服务(IUnitOfWork unitOfWork)
    {
    _unitOfWork=unitOfWork;
    }
    公共IEnumerable GetAll()
    {
    return _unitOfWork.Jobs.GetAll();
    }
    }
    
    这里我用接口来实现一切,如果你想做同样的事情,你需要使用IoC容器。我用的是“简单注入器”,你可以在这里找到它:

    另一个建议,如果你觉得有太多的I/O操作要执行,比如数据库访问、查询数据等,你应该考虑使用异步。下面是一个异步的好视频。