我是靠谱客的博主 俊逸人生,这篇文章主要介绍Asp.Net Core中创建多DbContext并迁移到数据库的步骤,现在分享给大家,希望可以做个参考。

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

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

  1 创建AuthorityDbContext

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class AuthorityDbContext : AbpZeroDbContext<Tenant, Role, User, AuthorityDbContext> {         /* Define a DbSet for each entity of the application */           public DbSet<UserMapping> UserMappings { get; set; }           public SunlightDbContext(DbContextOptions<SunlightDbContext> 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接口实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <summary>    /// 用于 EF Core Migration 时创建 DbContext,数据库连接信息来自 XXX.Dcs.WebHost 项目 appsettings.json    /// </summary>    public class AuthorityDesignTimeDbContextFactory : IDesignTimeDbContextFactory<AuthorityDbContext> {        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<SunlightDbContext>();            builder.UseSqlServer(connectString);            return new SunlightDbContext(builder.Options);        }    }

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{   "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": {     "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中调用下面的代码,这个是有所不同的地方,具体我们来看看代码。 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 初始化 EF Core DbContext             var abpConnectionString = _appConfiguration.GetConnectionString("Default");             services.AddDbContext<SunlightDbContext>(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<SunlightDbContext>             // Abp DI 未自动注册该对象,故而特别处理             services.AddTransient(provider => {                 var builder = new DbContextOptionsBuilder<SunlightDbContext>();                 builder.UseSqlServer(abpConnectionString);                 return builder.Options;             });             var dcsConnectionString = _appConfiguration.GetConnectionString("DcsEntity");             services.AddDbContext<DcsDbContext>(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并迁移到数据库的步骤的详细内容,更多关于Asp.Net Core创建多DbContext并迁移到数据库的资料请关注靠谱客其它相关文章!

最后

以上就是俊逸人生最近收集整理的关于Asp.Net Core中创建多DbContext并迁移到数据库的步骤的全部内容,更多相关Asp.Net内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(113)

评论列表共有 0 条评论

立即
投稿
返回
顶部