44

I am building web APIs in ASP.NET Core 1.1.

I have a number different databases (for different systems) which have common base schemas for configuration items such as Configuration, Users and groups (about 25 tables in all). I am trying to avoid duplicating the quite extensive EF configuration for the shared part of the model by inheriting from a base class as shown in the diagram.

My DbContext inheritance tree

However, this does not work because of the Entity Framework (EF) requirement to pass DbContextOptions<DerivedRepository> as a parameter to the constructor, where DerivedRepository must match the type of the repository the constructor is called on. The parameter must then be passed down to the base DbContext by calling :base(param).

So when (for example) InvestContext is initialised with DbContextOptions<InvestContext>, it calls base(DbContextOptions<InvestContext>) and EF throws an error because the call to the ConfigurationContext constructor is receiving a parameter of type DbContextOptions<InvestContext> instead of the required type DbContextOptions<ConfigurationContext>. Since the options field on DbContext is defined as

    private readonly DbContextOptions _options;

I can't see a way around this.

What is the best way to define the shared model once and use it multiple times? I guess I could create a helper function and call it from every derived context, but it's not nearly as clean or transparent as inheritance.

3 Answers 3

85

I would like to bring this post from the OP's GitHub issue to everyone's attention:

I was able to resolve this without a hack by providing a protected constructor that uses DbContextOptions without any type. Making the second constructor protected ensures that it will not get used by DI.

public class MainDbContext : DbContext {
    public MainDbContext(DbContextOptions<MainDbContext> options)
        : base(options) {
    }

    protected MainDbContext(DbContextOptions options)
        : base(options) {
    }
}

public class SubDbContext : MainDbContext {
    public SubDbContext (DbContextOptions<SubDbContext> options)
        : base(options) {
    }
}
5
  • 8
    this should be the accepted answer. Looks like this will be added to the official documentation as the suggested pattern in this case. github.com/aspnet/EntityFramework.Docs/issues/594
    – stonemusic
    Oct 11, 2019 at 4:18
  • 2
    This saved me after a few hours of debugging and trying different things. Works like a charm Apr 5, 2020 at 17:57
  • 1
    Wow bru I spent hours on this. Thank you so much.
    – D2TheC
    May 29, 2020 at 15:49
  • Worked perfectly.
    – Yogi
    Oct 20, 2020 at 18:47
  • 1
    This should be the accepted answer and it matches the documentation. It could still be supplemented with a note explaining what to configure in the services when starting the application. In my opinion, one should invoke builder.Services.AddDbContext for each derived class. Jun 20, 2022 at 17:03
25

OK, I have got this working in a way which still uses the inheritance hierarchy, like this (using InvestContext from above as the example):

As stated, the InvestContext class receives a constructor parameter of type DbContextOptions<InvestContext>, but must pass DbContextOptions<ConfigurationContext> to it's base.

I have written a method which digs the connectionstring out of a DbContextOptions variable, and builds a DbContextOptions instance of the required type. InvestContext uses this method to convert its options parameter to the right type before calling base().

The conversion method looks like this:

    protected static DbContextOptions<T> ChangeOptionsType<T>(DbContextOptions options) where T:DbContext
    {
        var sqlExt = options.Extensions.FirstOrDefault(e => e is SqlServerOptionsExtension);

        if (sqlExt == null)
            throw (new Exception("Failed to retrieve SQL connection string for base Context"));

        return new DbContextOptionsBuilder<T>()
                    .UseSqlServer(((SqlServerOptionsExtension)sqlExt).ConnectionString)
                    .Options;
    }

and the InvestContext constructor call changes from this:

  public InvestContext(DbContextOptions<InvestContext> options):base(options)

to this:

  public InvestContext(DbContextOptions<InvestContext> options):base(ChangeOptionsType<ConfigurationContext>(options))

So far both InvestContext and ConfigurationContext work for simple queries, but it seems like a bit of a hack and possibly not something the designers of EF7 had in mind.

I am still concerned that EF is going to get itself in a knot when I try complex queries, updates etc. It appears that this is not a problem, see below)

Edit: I've logged this problem as an issue with the EF7 team here, and a team member has suggested a change to the EF Core core as follows:

"We should update the check to allow TContext to be a type that is derived from the current context type"

This would solve the problem.

After further interaction with that team member (which you can see on the issue) and some digging through the EF Core code, the approach I've outlined above looks safe and the best approach until the suggested change is implemented.

4

Depending on your requirements you can simply use the non type specific version of DbContextOptions.

Change these:

public ConfigurationContext(DbContextOptions<ConfigurationContext> options):base(options)    
public InvestContext(DbContextOptions<InvestContext> options):base(options)

to this:

public ConfigurationContext(DbContextOptions options):base(options) 
public InvestContext(DbContextOptions options):base(options)

Then if you create your ConfigurationContext first, the classes that inherit it seem to get the same configuration. It may also depend on the order in which you initialize the different contexts.

Edit: My working example:

public class QueryContext : DbContext
{
    public QueryContext(DbContextOptions options): base(options)
    {
    }
}

public class CommandContext : QueryContext
{
    public CommandContext(DbContextOptions options): base(options)
    {
    }
}

And in Startup.cs

services.AddDbContext<CommandContext>(options =>
                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddDbContext<QueryContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

alternatively, in a test class:

    var connectionString = "Data Source=MyDatabase;Initial Catalog=MyData;Integrated Security=SSPI;";

    var serviceProvider = new ServiceCollection()
        .AddDbContext<QueryContext>(options => options.UseSqlServer(connectionString))
        .BuildServiceProvider();

    _db = serviceProvider.GetService<QueryContext>();
8
  • 1
    Do you actually have code which does this, and if so what version of EF7 are you running? Because when I try this DbContextOptions is abstract, and even if I implement a derived class (DbCo) I get the compile time error calling the constructor: "DbCo is not assignable to parameter type DbContextOptions<DerivedContext>". Looking in the EF7 code base at the DbContext constructor, there is a check there for options.ContextType.GetTypeInfo().IsAssignableFrom(GetType().GetTypeInfo()), so the DbContextOptions must be a generic derivative typed as the DerivedContext.
    – Peter
    Feb 7, 2017 at 13:34
  • Yes, I have this working, both from my application and in a test host configuration. I'm using Microsoft.EntityFrameworkCore 1.1.0. You may need to remove the <DerivedContext> from the type in the context constructor Feb 7, 2017 at 16:11
  • I have edited my question, adding the details of my attempt to implement your suggestion (not enough space in a comment). I get the error I expected, given the check I see in the EntityFramework code base. As far as I can see, the only way to avoid that error would be to call base() instead of base(options), which I think would lead to other problems if you are initialising multiple contexts. Could you perhaps extend your answer with more comprehensive code sample showing DerivedContext definition and usage? Thanks!
    – Peter
    Feb 8, 2017 at 11:02
  • My examples added. I don't see much difference, but may help. Feb 8, 2017 at 23:39
  • OK, yes, I did quite a bit of fiddling with this here, and it works with some serious caveats which aren't immediately obvious. Firstly, each call to AddDbContext appears to register DbContextOptions with the DI, meaning that the last context registered will be the type of the DbContextOptions passed to all DbContexts whose constructors specify a non-generic parameter. Implications: all contexts get the same options (incl. connection string); context which inherist from DbContext must be registered last; (see next comment)
    – Peter
    Feb 9, 2017 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.