Asp.Net Core中创建多DbContext并迁移到数据库的步骤
在我们的项目中我们有时候需要在我们的项目中创建DbContext,而且这些DbContext之间有明显的界限,比如系统中两个DbContext一个是和整个数据库的权限相关的内容而另外一个DbContext则主要是和具体业务相关的内容,这两个部分彼此之间可以分开,那么这个时候我们就可以在我们的项目中创建两个不同的DbContext,然后分别注入进去,当然这两个DbContext可以共用一个ConnectionString,也可以分别使用不同的DbContext,这个需要根据不同的需要来确定,在我们建立完了不同的DbContext的时候,我们就需要分别将每一个DbContext修改的内容迁移到数据库里面去,这个就涉及到数据库Migration的问题了,所以整篇文章主要围绕如何创建多个DbContext和每个DbContext的Migration的问题。
下面我们通过代码来创建两个不同的DbContext
1创建AuthorityDbContext
publicclassAuthorityDbContext:AbpZeroDbContext{ /*DefineaDbSetforeachentityoftheapplication*/ publicDbSet UserMappings{get;set;} publicSunlightDbContext(DbContextOptions options) :base(options){ } protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder){ base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfiguration(newTenantConfiguration()); //请在此处填写所有与具体数据库无关的Model调整,确保单元测试可以覆盖 if(Database.IsInMemory()) return; } }
这个DbContext主要用来做一些和身份验证以及权限相关的操作,这里只是定义了一个最简单的结构,后面的一个DbContext就是具体业务相关的内容,在我们的项目中,我们两个DbContext会使用相同的连接字符串。
2 IDesignTimeDbContextFactory接口实现
//////用于EFCoreMigration时创建DbContext,数据库连接信息来自XXX.Dcs.WebHost项目appsettings.json /// publicclassAuthorityDesignTimeDbContextFactory:IDesignTimeDbContextFactory{ privateconststringDefaultConnectionStringName="Default"; publicSunlightDbContextCreateDbContext(string[]args){ varconfiguration=AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder()); varconnectString=configuration.GetConnectionString(DefaultConnectionStringName); varbuilder=newDbContextOptionsBuilder (); builder.UseSqlServer(connectString); returnnewSunlightDbContext(builder.Options); } }
在了解这段代码之前,你可以先了解一下这个到底是做什么用的,就像注释里面说的,当我们使用EFCoreMigration的时候,这里会默认读取WebHost项目里面的appsettings.json里面的Default配置的连接字符串。
{ "ConnectionStrings":{ "Default":"Server=XXXX,XX;Database=XXXX;UserId=XXXX;Password=XXXX;", "DcsEntity":"Server=XXXX,XX;Database=XXXX;UserId=XXXX;Password=XXXX;" }, "Redis":{ "Configuration":"127.0.0.1:XXXX", "InstanceName":"XXXX-Sales" }, "App":{ "ServerRootAddress":"http://localhost:XXXX/", "ClientRootAddress":"http://localhost:XXXX/", "CorsOrigins":"http://localhost:XX,http://localhost:XX,http://localhost:XX" }, "Kafka":{ "BootstrapServers":"127.0.0.1:XX", "MessageTimeoutMs":5000, "Topics":{ "CustomerAndVehicleEvent":"XXXX-customer-update", "AddOrUpdateProductCategoryEvent":"XXXX-add-update-product-category", "AddOrUpdateDealerEvent":"XXXX-add-update-dealer", "ProductUpdateEvent":"XXXX-product-update", "VehicleInformationUpdateStatusEvent":"XXXX-add-update-vehicle-info", "AddCustomerEvent":"cowin-add-customer" } }, "Application":{ "Name":"XXXX-sales" }, "AppSettings":{ "ProductSyncPeriodMi":60, "DealerSyncPeriodMi":60 }, "Eai":{ "Authentication":{ "Username":"2XXX2", "Password":"XXXX" }, "Services":{ "SapFinancial":"http://XXXX:XXXX/OSB_MNGT/Proxy/XXXX" } }, "DependencyServices":{ "BlobStorage":"http://XXXX-XXXX/" }, "Authentication":{ "JwtBearer":{ "IsEnabled":true, "Authority":"http://XXXX/", "RequireHttpsMetadata":false } }, "Sentry":{ "IncludeRequestPayload":true, "SendDefaultPii":true, "MinimumBreadcrumbLevel":"Debug", "MinimumEventLevel":"Warning", "AttachStackTrace":true }, "Logging":{ "LogLevel":{ "Default":"Warning" } } }
3DBMigration
有了上面的工作之后,我们就能够进行数据库迁移并更新到数据库了,主要过程分为2步Add-MigrationXXX和Update-Database-verbose两步,只不过是现在我们想构建多个DbContext,所以我们需要通过参数-cxxxDbContext来指定具体的DbContext,否则会报下面的错误。MorethanoneDbContextwasfound.Specifywhichonetouse.Usethe'-Context'parameterforPowerShellcommandsandthe'--context'parameterfordotnetcommands.
有了这些以后,我们就可以更新到数据库了,在更新的时候记住要指定DbContext,更新时使用下面的命令:Update-Database-verbose-cXXXDbContext。
4创建第二个DbContext
有了前面的过程,创建第二个DbContext的过程就比较简单了,重复上面的步骤一、二、三,然后完成第二个DbContext的创建和数据库的迁移,但是这里我们需要注意一些不同之处,第一个由于我们想要使用ABP框架中的多租户相关的一些实体,所以这里我们构建的基类是继承自AbpZeroDbContext,后面我们创建的业务相关的DbContext的时候,我们不需要这些,所以我们只需简单继承自AbpDbContext即可。
5Startup中初始化EFCoreDbContext
这个和之前创建一个DbContext有所不同的是我们需要向Asp.NetCore依赖注入容器中两次注入不同的DbContext,在Asp.NetCore中该如何创建DbContext并实现注入,请点击这里参考官方文档,在这里我们需要在Startup中的ConfigureServices中调用下面的代码,这个是有所不同的地方,具体我们来看看代码。
//初始化EFCoreDbContext varabpConnectionString=_appConfiguration.GetConnectionString("Default"); services.AddDbContext(options=>{ options.UseSqlServer(abpConnectionString); if(Environment.IsDevelopment()){ options.EnableSensitiveDataLogging(); //https://docs.microsoft.com/en-us/ef/core/querying/client-eval#optional-behavior-throw-an-exception-for-client-evaluation options.ConfigureWarnings(warnings=>warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)); } }); //AuthConfigurer.MapUserIdentity需使用DbContextOptions //AbpDI未自动注册该对象,故而特别处理 services.AddTransient(provider=>{ varbuilder=newDbContextOptionsBuilder (); builder.UseSqlServer(abpConnectionString); returnbuilder.Options; }); vardcsConnectionString=_appConfiguration.GetConnectionString("DcsEntity"); services.AddDbContext (options=>{ options.UseSqlServer(dcsConnectionString); if(Environment.IsDevelopment()){ options.EnableSensitiveDataLogging(); //https://docs.microsoft.com/en-us/ef/core/querying/client-eval#optional-behavior-throw-an-exception-for-client-evaluation options.ConfigureWarnings(warnings=>warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)); } });
这样就能够在服务具体运行的过程中来添加具体的DbContext啦,经过上面的过程我们就能够实现在一个项目中添加多个DbContext,并迁移数据库整个过程。
以上就是Asp.NetCore中创建多DbContext并迁移到数据库的步骤的详细内容,更多关于Asp.NetCore创建多DbContext并迁移到数据库的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。