EntityFramework 6 DbContext with an interface

I recently migrated one of our projects to EntityFramework 6’s Code-First framework. There weren’t a great deal of differences in the underlying models, but the context class changed a fair amount. My project is loaded with over 300 unit tests that interact with the EntityFramework models. Prior to the upgrade, I was able to accomplish this (without hitting an actual database) by create a mock framework for the entity context. The most important aspect of this was to use an interface with the entity context so that I could reference the interface rather than a concrete instance of the context class. In EF6’s code-first model, I ran into some issues using an interface.

When I applied my interface to the new entity context generated by EF6’s code-first model creation tool, I managed to get it to compile just fine. However, during run-time, I received the following error:

Multiple object sets per type are not supported. The object sets ‘XXXXX’ and ‘My.Namespace.XXXXX’ can both contain instances of type ‘My.Namespace.XXXXX’.

My interface looked like this:

public interface IRepository
{
    IDbSet<MyObject> MyObjects { get; }
}

The problem with this interface, and the reason the error was appearing, was because I was using IDbSet<> in my interface, rather than DbSet<>.

If you change the interface to use concrete DbSet<> instances instead of IDbSet<>, the error goes away.

public interface IRepository
{
    DbSet<MyObject> MyObjects { get; }
}

Leave a Reply

Your email address will not be published.

Humanity Verification *Captcha loading...