.NetCore 下使用多个DbContext

时间:2024-01-02 19:53:56

一个项目中使用多个DbContext 或者种数据库的多个DbContext 业务需要

单个DbContext使用不需要给出说明

1、dotnet ef migrations add migrationname

2、dotnet ef database update

多个DbContext请使用如下命令指定dbcontext名称或者指定生成到目录

1、 添加为dbcontextname 添加 migrations 到 pathdir目录下面,这里需要注意的是应用程序集目录问题 _migrationAssablyName,会决定生成migraions文件夹位置

dotnet ef migrations add migrationname -c dbcontextname -o pathdir

services.AddDbContext<UserDbContext>(
optionsBuilder =>
{
var _userappsetting = Configuration.GetSection("UserAppSetting").Get<UserAppSetting>();
if (_userappsetting == null)
{
throw new Exception("数据库连接字符串未配置");
}
switch (_userappsetting.DbType)
{
case :
optionsBuilder.UseSqlServer(_userappsetting.UserConnectionString, sqlserver =>
{
sqlserver.MigrationsAssembly(_migrationAssablyName); sqlserver.UseRowNumberForPaging(); });
break; default:
optionsBuilder.UseMySQL(_userappsetting.UserConnectionString, mysql =>
{
mysql.MigrationsAssembly(_migrationAssablyName); });
break; }
});
 "UserAppSetting": {
//server=192.168.0.42;port=3306;user=root;password=lym123!@#; database=Edu_User;SslMode=none;
"UserConnectionString": "Data Source=192.168.0.42;Initial Catalog=Edu_User;User ID=sa;password=lym123!@#;Integrated Security=false;",
//
"ReadConnectionString": "Data Source=192.168.0.42;Initial Catalog=Edu_User;User ID=sa;password=lym123!@#;Integrated Security=false;",
"DbType": //数据库类型
}

2、更新 填写需要更新的DbContext对象即可

dotnet ef database update -c dbcontextname