Multiple dbContexts in ASP.NET vNext and EF7 c# entity-framework entity-framework-core


I'm trying to get along with building web systems with ASP.NET vNext using MVC 6 and EF7. I'm looking at this tutorial:

On the page you'll see how to add a dbContext to a project and it's registered in the startup file like this:

// Register Entity Framework

And the context class looks like this:

public class MoviesAppContext:DbContext
    public DbSet<Movie> Movies { get; set; }

It all works good, but now I'm in need of adding an additional DbContext. Though I don't know how to register this additional context so that it will be used by EF and possible to use in my project.

Let's say I've created a new context like this:

public class MyNewSuper:DbContext
    public DbSet<Model1> Model1 { get; set; }
    public DbSet<Model2> Model2 { get; set; }

How do I go ahead to register it for use in my project then?

4/26/2015 2:39:04 AM

Popular Answer

Important Note: The syntax for configuring the Entity Framework 7 services has changed since this post, which was accurate as of the last few beta rounds. The same idea should still apply to the new syntax though.

Here is what I've been doing:

                .AddDbContext<DataContextA>(options => options.UseSqlServer(Configuration.Get("StorageSettings:SQLConnectionString")))
                .AddDbContext<DataContextB>(options => options.UseSqlServer(Configuration.Get("StorageSettings:SQLConnectionString")));

where StorageSettings:SQLConnectionString is a connection string for a SQL Express database. Currently, I have both DataContextA and DataContextB sharing the same database, but you can keep them separate. If you want to keep using the Configuration method (which I wasn't aware of, pretty cool!) you could do something like this:

    "Data": {
        "DefaultConnectionA": { 
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ContextADatabase;Trusted_Connection=True;MultipleActiveResultSets=true",
        "DefaultConnectionB": { 
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ContextBDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
    "EntityFramework": {
        "DataContextA": {
            "ConnectionStringKey": "Data:DefaultConnectionA:ConnectionString"
        "DataContextB": {
            "ConnectionStringKey": "Data:DefaultConnectionB:ConnectionString"



Both DataContextA and DataContextB can be injected into your controller:

public class MyController: Controller {
    public MyController(DataContextA dataA, DataContextB dataB) {
        // Do stuff
6/7/2016 5:31:26 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow