Multiple dbContexts in ASP.NET vNext and EF7

前端 未结 2 1368
忘了有多久
忘了有多久 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:19

    First of all, in something like config.json you can add yur connection strings. Something like the following will work

      "Data": {
        "BlogData": { "ConnectionString": "Server=tcp:YourHostname.net,1433;Database=YourDatabaseName;User ID=YourDBUser@YourDomain;Password=YourPassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" },
        "Identity": { "ConnectionString": "Server=tcp:YourHostname.net,1433;Database=YourDatabaseName;User ID=YourDBUser@YourDomain;Password=YourPassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" }
      },
    

    You then have two DBContexts. Let's say: YourApp.AppDBContext and YourApp.AppIdentityDBContext

    You need to include these at the top of your CS file of course.

    using YourApp.AppDBContext;
    using YourApp.AppIdentityDBContext;
    

    In startup.cs for example, in the startup method, your configuration builder will look like this:

        var builder = new ConfigurationBuilder()
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }
    

    In the ConfigureServices method you will add your DBContexts as follows:

        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext(options =>
                options.UseSqlServer(Configuration["Data:BlogData:ConnectionString"]))
            .AddDbContext(options =>
                options.UseSqlServer(Configuration["Data:Identity:ConnectionString"]));
    

    I hope this helps. Feel free to give me a shout if I can expand on this further.

提交回复
热议问题