Why DbContext doesn't implement IDbContext interface?

Entity FrameworkUnit TestingTestingMockingMoq

Entity Framework Problem Overview


Why there is no IDbContext interface in the Entity Framework? Wouldn't it be easier to test things if there was an existing interface with methods like SaveChanges() etc. from which you could derive your custom database context interface?

public interface ICustomDbContext : IDbContext
{
    // add entity set properties to existing set of methods in IDbContext
    IDbSet<SomeEntity> SomeEntities { get; }
}

Entity Framework Solutions


Solution 1 - Entity Framework

I see this IDbContext:

See this link And then you make a new partial class for your Entities Context With That interface.

public partial class YourModelEntities : DbContext, IDbContext 

EDITED: I edited this post, This Works for me. My Context

namespace dao
{
    public interface ContextI : IDisposable
    {
        DbSet<TEntity> Set<TEntity>() where TEntity : class;
        DbSet Set(Type entityType);
        int SaveChanges();
        IEnumerable<DbEntityValidationResult> GetValidationErrors();
        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity:class;
        DbEntityEntry Entry(object entity);
        string ConnectionString { get; set; }
        bool AutoDetectChangedEnabled { get; set; }
        void ExecuteSqlCommand(string p, params object[] o);
        void ExecuteSqlCommand(string p);
    }
}

YourModelEntities is your auto-generated partial class, and your need to create a new partial class with the same name, then add your new context interface, for this example is ContextI

NOTE: The interface hasn't implement all methods, because the methods are implemented in your auto-generate code.

namespace dao
{
    public partial class YourModelEntities :DbContext, ContextI
    {
        public string ConnectionString
        {
            get
            {
                return this.Database.Connection.ConnectionString;
            }
            set
            {
                this.Database.Connection.ConnectionString = value;
            }
        }

        bool AutoDetectChangedEnabled
        {
            get
            {
                return true;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void ExecuteSqlCommand(string p,params object[] os)
        {
            this.Database.ExecuteSqlCommand(p, os);
        }

        public void ExecuteSqlCommand(string p)
        {
            this.Database.ExecuteSqlCommand(p);
        }

        bool ContextI.AutoDetectChangedEnabled
        {
            get
            {
                return this.Configuration.AutoDetectChangesEnabled;
            }
            set
            {
                this.Configuration.AutoDetectChangesEnabled = value;
            }
        }
      
    }
}

Solution 2 - Entity Framework

I was thinking also about that, I assume you are going to use it for mocking DbContext. I find no reason for that, except that you will need to implement your own DbSet manually in your anyway for your mocked class (so will need to rewrite your own interface anyway).

Solution 3 - Entity Framework

Just create a mock DbContext extending your production DbContext overriding the methods that complicate testing. That way, any changes to the production DbContext are automatically reflected in the tests, save for the overridden methods. For any other classes that deal with persistence and take the DbContext just extend them as well passing in the extended mock DbContext.

namespace Test.Mocks
{  
    public sealed class MockDatabaseContext : MainProject.Persistence.Database.DatabaseContext
    {
        public MockDatabaseContext(ConfigurationWrapper config) : base(config)
        {
                
        }      
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            
            var dbPath = "test.db";
            optionsBuilder.UseSqlite($"Filename={dbPath}");
                          
           
        }
    }
}

namespace Test.Mocks
{
   
    public class MockInventoryFacade : InventoryFacade
    {        
        public MockInventoryFacade(MockDatabaseContext databaseContext) : base(databaseContext)
        {
         
        }    
    }
}

Solution 4 - Entity Framework

There is no IDbContext because it would be useless, the only implementation of it would be the DbContext.

EF team is also going this way with IDbSet if you look at this design meeting note

For me, the real problem with EF when it comes to unit testing is the DbConnection in the DbContext, fortunately there is Effort a nice project on codeplex that starts to fill this.

> Effort is a powerful tool that enables a convenient way to create automated tests for Entity Framework based applications. It is basically an ADO.NET provider that executes all the data operations on a lightweight in-process main memory database instead of a traditional external database. It provides some intuitive helper methods too that make really easy to use this provider with existing ObjectContext or DbContext classes. A simple addition to existing code might be enough to create data driven tests that can run without the presence of the external database.

With this, you can leave your DbContext and DbSet as is and do your unit tests easily. The only drawback with this is the difference between Linq providers where some unit tests may pass with effort and not with the real backend.

UPDATE with EF7

I still maintain that IDbContext would be useless and the problem comes from the DbConnection.

EF7 will not have an IDbContext either, in order to do unit testing they are now giving an in memory provider.

You can see Rowan Miller doing a demo here: Modern Data Applications with Entity Framework 7

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGrief CoderView Question on Stackoverflow
Solution 1 - Entity Frameworkuser1626116View Answer on Stackoverflow
Solution 2 - Entity FrameworkMohammed NoureldinView Answer on Stackoverflow
Solution 3 - Entity FrameworkSean AndersonView Answer on Stackoverflow
Solution 4 - Entity FrameworkJuChomView Answer on Stackoverflow