• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Asp.Net Core中创建多DbContext并迁移到数据库的步骤

asp 搞代码 4年前 (2022-01-03) 45次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了Asp.Net Core中创建多DbContext并迁移到数据库的步骤,帮助大家更好的理解和学习使用Asp.Net Core,感兴趣的朋友可以了解下

  在我们的项目中我们有时候需要在我们的项目中创建DbContext,而且这些DbContext之间有明显的界限,比如系统中两个DbContext一个是和整个数据库的权限相关的内容而另外一个DbContext则主要是和具体业务相关的内容,这两个部分彼此之间可以分开,那么这个时候我们就可以在我们的项目中创建两个不同的DbContext,然后分别注入进去,当然这两个DbContext可以共用一个ConnectionString,也可以分别使用不同的DbContext,这个需要根据不同的需要来确定,在我们建立完了不同的DbContext的时候,我们就需要分别将每一个DbContext修改的内容迁移到数据库里面去,这个就涉及到数据库Migration的问题了,所以整篇文章主要围绕如何创建多个DbContext和每个DbContext的Migration的问题。 

  下面我们通过代码来创建两个不同的DbContext

  1 创建AuthorityDbContext

 public class AuthorityDbContext : AbpZeroDbContext {         /* Define a DbSet for each entity of the application */           public DbSet UserMappings { get; set; }           public SunlightDbContext(DbContextOptions options)             : base(options) {         }           protected override void OnModelCreating(ModelBuilder modelBuilder) {             base.OnModelCreating(modelBuilder);             modelBuilder.ApplyConfiguration(new TenantConfiguration());               // 请在此处填写所有与具体数据库无关的 Model 调整,确保单元测试可以覆盖               if (Database.IsInMemory())                 return;                    }              }

  这个DbContext主要用来做一些和身份验证以及权限相关的操作,这里只是定义了一个最简单的结构,后面的一个DbContext就是具体业务相关的内容,在我们的项目中,我们两个DbContext会使用相同的连接字符串。

  2 IDesignTimeDbContextFactory接口实现

 /// <summary>    /// 用于 EF Core Migration 时创建 DbContext,数据库连接信息来自 XXX.Dcs.WebHost 项目 appsettings.json    /// </summary>    public class AuthorityDesignTimeDbContextFactory : IDesignTimeDbContextFactory {        private const string DefaultConnectionStringName = "Default";          public SunlightDbContext CreateDbContext(string[] args) {            var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());            var connectString = configuration.GetConnectionString(DefaultConnectionStringName);              var builder = new DbContextOptionsBuilder();            builder.UseSqlServer(connectString);            return new SunlightDbContext(builder.Options);        }    }

  在了解这段代码之前,你可以先了解一下这个到底是做什么用的,就像注释里面说的,当我们使用EFCore Migration的时候,这里会默认读取WebHost项目里面的appsettings.json里面的Default配置的连接字符串。

 {   "ConnectionStrings": {     "Default": "Server=XXXX,XX;Database=XXXX;User Id=XXXX;Password=XXXX;",     "DcsEntity": "Server=XXXX,XX;Database=XXXX;User Id=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": {     <a style="color:transparent">来源gao($daima.com搞@代@#码网</a>"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"     }   } }

  3 DB Migration

  有了上面的工作之后,我们就能够进行数据库迁移并更新到数据库了,主要过程分为2步Add-Migration XXX和Update-Database -verbose两步,只不过是现在我们想构建多个DbContext,所以我们需要通过参数-c xxxDbContext来指定具体的DbContext ,否则会报下面的错误。More than one DbContext was found. Specify which one to use. Use the ‘-Context’ parameter for PowerShell commands and the ‘–context’ parameter for dotnet commands.

  有了这些以后,我们就可以更新到数据库了,在更新的时候记住要指定DbContext,更新时使用下面的命令:Update-Database -verbose -c XXXDbContext。

  4 创建第二个DbContext

  有了前面的过程,创建第二个DbContext的过程就比较简单了,重复上面的步骤一、二、三,然后完成第二个DbContext的创建和数据库的迁移,但是这里我们需要注意一些不同之处,第一个由于我们想要使用ABP框架中的多租户相关的一些实体,所以这里我们构建的基类是继承自AbpZeroDbContext,后面我们创建的业务相关的DbContext的时候,我们不需要这些,所以我们只需简单继承自AbpDbContext即可。

  5 Startup中初始化EF Core DbContext

  这个和之前创建一个DbContext有所不同的是我们需要向Asp.Net Core依赖注入容器中两次注入不同的DbContext,在Asp.Net Core中该如何创建DbContext并实现注入,请点击这里参考官方文档,在这里我们需要在Startup中的ConfigureServices中调用下面的代码,这个是有所不同的地方,具体我们来看看代码。 

 // 初始化 EF Core DbContext             var abpConnectionString = _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             // Abp DI 未自动注册该对象,故而特别处理             services.AddTransient(provider => {                 var builder = new DbContextOptionsBuilder();                 builder.UseSqlServer(abpConnectionString);                 return builder.Options;             });             var dcsConnectionString = _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.Net Core中创建多DbContext并迁移到数据库的步骤的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Asp.Net Core中创建多DbContext并迁移到数据库的步骤

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址