how create dbcontext manually in entity framework different database connections?
first can have multiple named connection strings in app.config
file below:
<connectionstrings> <add name="todoconnectionstring" connectionstring="data source=mylocalbox;initial catalog=tododbcodefirst2;integrated security=true;multipleactiveresultsets=true;" providername="system.data.sqlclient" /> <add name="stackoverflowentities" connectionstring="metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=system.data.sqlclient;provider connection string="data source=.;initial catalog=stackoverflow;integrated security=true;multipleactiveresultsets=true;app=entityframework"" providername="system.data.entityclient" /> </connectionstrings>
now can define 2 different custom classes inherited dbcontext
class shown below:
using system.data.entity; namespace efdevelopment { public class todocodefirstdbcontext : dbcontext { public todocodefirstdbcontext() : base("name=todoconnectionstring")//connection string 1st db { } public dbset<todo> todos { get; set; } } public class todocodeseconddbcontext : dbcontext { public todocodeseconddbcontext() : base("name=stackoverflowentities")//connection string 2nd db { } public dbset<todo> todos { get; set; } } }
now inside main program (i've used console application) instantiate respective entity framework (ef) context classes per need of connecting them appropriate database shown below:
class program { static void main(string[] args) { using (var db = new todocodefirstdbcontext()) { //write code here first db connection } using (var db = new todocodeseconddbcontext()) { //write code here second db connection } } }
Comments
Post a Comment