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


i'm trying along building web systems asp.net vnext using mvc 6 , ef7. i'm looking @ tutorial: http://stephenwalther.com/archive/2015/01/17/asp-net-5-and-angularjs-part-4-using-entity-framework-7

on page you'll see how add dbcontext project , it's registered in startup file this:

// register entity framework services.addentityframework(configuration)         .addsqlserver()         .adddbcontext<moviesappcontext>(); 

and context class looks this:

public class moviesappcontext:dbcontext {     public dbset<movie> movies { get; set; } } 

it works good, i'm in need of adding additional dbcontext. though don't know how register additional context used ef , possible use in project.

let's i've created new context this:

public class mynewsuper:dbcontext {     public dbset<model1> model1 { get; set; }     public dbset<model2> model2 { get; set; } } 

how go ahead register use in project then?

important note: syntax configuring entity framework 7 services has changed since post, accurate of last few beta rounds. same idea should still apply new syntax though.

here i've been doing:

services.addentityframework().addsqlserver()                 .adddbcontext<datacontexta>(options => options.usesqlserver(configuration.get("storagesettings:sqlconnectionstring")))                 .adddbcontext<datacontextb>(options => options.usesqlserver(configuration.get("storagesettings:sqlconnectionstring"))); 

where storagesettings:sqlconnectionstring connection string sql express database. currently, have both datacontexta , datacontextb sharing same database, can keep them separate. if want keep using configuration method (which wasn't aware of, pretty cool!) 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<datacontexta>()                 .adddbcontext<datacontextb>(); 

both datacontexta , datacontextb can injected controller:

public class mycontroller: controller {     public mycontroller(datacontexta dataa, datacontextb datab) {         // stuff     } } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -