Multiple dbContexts in ASP.NET vNext and EF7

前端 未结 2 1410
忘了有多久
忘了有多久 2021-02-06 12:26

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: http://stephenwalther.com/archive/2015/01/17/asp-net-5-

2条回答
  •  北海茫月
    2021-02-06 13:05

    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:

    services.AddEntityFramework().AddSqlServer()
                    .AddDbContext(options => options.UseSqlServer(Configuration.Get("StorageSettings:SQLConnectionString")))
                    .AddDbContext(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"
            }
        }
    }
    

    with

    services.AddEntityFramework(Configuration)
                    .AddSqlServer()
                    .AddDbContext()
                    .AddDbContext();
    

    Both DataContextA and DataContextB can be injected into your controller:

    public class MyController: Controller {
        public MyController(DataContextA dataA, DataContextB dataB) {
            // Do stuff
        }
    }
    

提交回复
热议问题