use multiple dbContext in one application

你。 提交于 2021-01-29 12:51:56

问题


I am struggling with using multiple dbContext with an single web application in ASP.NET MVC 5. I am following code First existing database design approach.

i need guideline how to do that say in example if i am creating 5 models using ADO.NET, it will create 5 dbContext along with its model classes.

how it will change in web.config file?

Many Thanks

 public partial class DefaultContext : DbContext
{
    public DefaultContext()
        : base("name=DefaultContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
    public virtual DbSet<sys_Actions> sys_Actions { get; set; }
    public virtual DbSet<sys_ActionsInRole> sys_ActionsInRole { get; set; }
    public virtual DbSet<sys_Controllers> sys_Controllers { get; set; }
    public virtual DbSet<sys_Functions> sys_Functions { get; set; }
    public virtual DbSet<sys_FunctionsHierarchy> sys_FunctionsHierarchy { get; set; }
}

回答1:


basically for each dbContext you need to add a new connection string with unique name in the connectionStrings section in your web.config file

here is an example:

<connectionStrings>
    <add name="dbContext1" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=dbServer;initial catalog=db1;integrated security = true;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="dbContext2" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=dbServer;initial catalog=db1;integrated security = true;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>


来源:https://stackoverflow.com/questions/20494551/use-multiple-dbcontext-in-one-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!