More than one DbContext in the same project

huangapple go评论94阅读模式
英文:

More than one DbContext in the same project

问题

我有一个WebAPI项目,在这个项目中,我必须使用多个DbContext,但我不知道如何做到这一点。
有3或4个数据库,使用Code First我将在每个数据库中创建一个新表,并将其与每个数据库中找到的表建立关系。

如何以一种通用的方式实现这一点?

英文:

I have a WebAPI project and in this project I have to use more than one DbContext but I do not know how to do that.
There are 3 or 4 databases and with code first I will create a new table in each of them and give relation to the table that is found in each database

How can I do this in a generic way?

答案1

得分: 1

有多个数据库。它们应该添加到服务中。
示例:

var connectionString1 = builder.Configuration.GetConnectionString("Db1Connection");
builder.Services.AddDbContext<DbfirstDbContext>(options =>
     options.UseSqlServer(connectionString1));

var connectionString2 = builder.Configuration.GetConnectionString("Db2Connection");
builder.Services.AddDbContext<DbtwoDbContext>(options =>
     options.UseSqlServer(connectionString2));
英文:

to have multiple databases. they should be added to the services.
example :

var connectionString1 = builder.Configuration.GetConnectionString(&quot;Db1Connection&quot;);
builder.Services.AddDbContext&lt;DbfirstDbContext&gt;(options =&gt;
     options. UseSqlServer(connectionString));

var connectionString2 = builder.Configuration.GetConnectionString(&quot;Db2Connection&quot;);
builder.Services.AddDbContext&lt;DbtwoDbContext&gt;(options =&gt;
     options. UseSqlServer(connectionString2));

</details>



huangapple
  • 本文由 发表于 2023年3月1日 15:40:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定