温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Asp.Net Core中如何创建多DbContext并迁移到数据库

发布时间:2021-03-06 10:19:09 来源:亿速云 阅读:275 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关Asp.Net Core中如何创建多DbContext并迁移到数据库的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

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

  1 创建AuthorityDbContext

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接口实现

/// <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配置的连接字符串。

{
  "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中调用下面的代码,这个是有所不同的地方,具体我们来看看代码。 

// 初始化 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并迁移到数据库”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI