Question

I'm using EF and MVVM pattern. My question is about the Data Access Layer. in DAL I have the following classes:

  1. MyObjectContext which is technically the standard ObjectContext now, but some Unit-of-work methods will be added to it later.

  2. Repository<TModel> which handles the most needed queries (such as Add, GetAll, ...) on different ObjectSets.

  3. A bunch of DataServices which make use of repositories to provide a higher level of data access for Core.

The project I'm working on is a business application with about 100 EntitySets so far, and there are times when a single interaction of a user can involve up to 20 different EntitySets (updating most of them). I currently add .Include(params string[]) to my queries to prevent ObjectContextDisposedException but it doesn't seem to be a reliable solution.

The question is should I create an instance of MyObjectContext (and therefore Repository) in each of DataService methods (like the following codes, it seems to me that the ability of Unit of work would be useless in this case) or should I create it outside of DataService and pass it to the DataServices through their constructors (or directly to each of the DataService methods) to handle a bunch of database actions (different tables and queries) together. And how?

Here's what MyObjectContext looks like:

public class MyObjectContext : ObjectContext, IUnitOfWork
{
    public MyObjectContext()
        : base("name=EdmContainer", "EdmContainer")
    {
        ContextOptions.LazyLoadingEnabled = true;
    }

    #region IUnitOfWork Members
    public void Commit()
    {
        SaveChanges();
    }
    #endregion
}

This is how Repository looks like:

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);
    }
    ...
}

And this is how a common DataService looks like:

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
}

Any kind of idea or insight would be appreciated.

Was it helpful?

Solution

You can create an instance of MyObjectContext in each service, like JobDataService, however, it makes your code messy and it is hard to maintain. Create instance of MyObjectContext outside of DataService is better. What you have now, if you have 100 EntitySets, you have to create 100 DataServices. That is because the use of "Repository Pattern" and "UnitOfWork" here is not efficient. I would suggest doing the following:

ObjectContext

public class MyObjectContext : ObjectContext
{
    public MyObjectContext() : base("name=EdmContainer", "EdmContainer")
    {
        ContextOptions.LazyLoadingEnabled = true;
    }

    #region IUnitOfWork Members
    public void Commit()
    {
        SaveChanges();
    }
    #endregion
}

Generic Repository

 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>();
        }
    }

UnitOfWork

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);
        }

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();
            }
        }

Here I used interface for implementing everything, if you want to do the same, you need to use IoC Container. I used the "Simple Injector", you can find it here:

Simple Injector

One more suggestion, if you feel like you have too many I/O operations to implement, like database access, querying data, etc., you should consider using Asynchronous. Below is a good video on Asynchronous.

How to Build ASP.NET Web Applications Using Async

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top