场景

在一个项目中,使用了多个 DbContext 且使用同一个数据库的情况

创建新项目

  • 打开 Visual Studio 2017

  • “文件”>“新建”>“项目”

  • 从左菜单中选择“已安装”>“Visual C#”>“.NET Core”。

  • 选择“ASP.NET Core Web 应用程序”。

  • 输入“WebApplication”作为名称,然后单击“确定”。

  • 在“新建 ASP.NET Core Web 应用程序”对话框中:

  • 确保在下拉列表中选择“.NET Core”和“ASP.NET Core 2.1”

  • 选择“Web 应用程序(模型视图控制器)”项目模板

  • 确保将“身份验证”设置为“无身份验证”

  • 单击“确定”

创建第一个模型

  • 右键单击“Models”文件夹,然后选择“添加”>“类”。

  • 输入“FirstModel.cs”作为名称,然后单击“确定”。

  • 将此文件的内容替换为以下代码:

    using System.Collections.Generic;
    using Microsoft.EntityFrameworkCore; namespace WebApplication.Models
    {
    public class FirstDbContext : DbContext
    {
    public FirstDbContext(DbContextOptions<FirstDbContext> options)
    : base(options)
    { } public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
    } public class Blog
    {
    public int BlogId { get; set; }
    public string Url { get; set; } public ICollection<Post> Posts { get; set; }
    } public class Post
    {
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; } public int BlogId { get; set; }
    public Blog Blog { get; set; }
    }
    }

    生产应用通常会将每个类放在单独的文件中。 为简单起见,本教程将这些类放在一个文件中。

创建第二个模型

  • 右键单击“Models”文件夹,然后选择“添加”>“类”。

  • 输入“SecondModel.cs”作为名称,然后单击“确定”。

  • 将此文件的内容替换为以下代码:

    using Microsoft.EntityFrameworkCore;
    
    namespace WebApplication.Models
    {
    public class SecondDbContext : DbContext
    {
    public SecondDbContext(DbContextOptions<SecondDbContext> options)
    : base(options)
    { } public DbSet<Student> Students { get; set; }
    } public class Student
    {
    public int Id { get; set; }
    public string Name { get; set; }
    }
    }

    生产应用通常会将每个类放在单独的文件中。 为简单起见,本教程将这些类放在一个文件中。

  • 至此,项目的目录结构如下:

使用依赖注入注册上下文

若要使 FirstDbContextSecondDbContext 可用于 MVC 控制器,请在 Startup.cs 中将其注册为服务。

在应用程序启动过程中,通过依赖关系注入 注册服务(如 FirstDbContext),以便能够通过构造函数的参数和属性向使用服务的组件(如 MVC 控制器)自动提供该服务。

  • 在 Startup.cs 中,添加以下 using 语句:

    using WebApplication.Models;
    using Microsoft.EntityFrameworkCore;
  • 将以下 手动高亮 的代码添加到 ConfigureServices 方法:

    public void ConfigureServices(IServiceCollection services)
    {
    services.Configure<CookiePolicyOptions>(options =>
    {
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
    }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); var connection = @"Server=你的数据库地址;Database=MultipleDbContext;User Id=你的数据库账号;Password=你的数据库密码;"; // 手动高亮
    services.AddDbContext<FirstDbContext> // 手动高亮
    (options => options.UseSqlServer(connection, x => x.MigrationsHistoryTable("__FirstDbMigrationsHistory"))); // 手动高亮 services.AddDbContext<SecondDbContext> // 手动高亮
    (options => options.UseSqlServer(connection, x => x.MigrationsHistoryTable("__SecondDbMigrationsHistory"))); // 手动高亮
    }

    生产应用通常会将连接字符串放在配置文件或环境变量中。 为简单起见,本教程在代码中定义它。

创建数据库

以下步骤使用迁移创建数据库。

  • “工具”>“NuGet 包管理器”>“包管理器控制台”

  • 运行以下命令创建 FirstDbContext 的迁移:

    Add-Migration InitialCreate -Context FirstDbContext -OutputDir Migrations\FirstDbContextMigrations
    Update-Database -Context FirstDbContext

    -Context 参数表示要使用的 DbContext 类,请参阅这里了解详细信息。

  • “工具”>“NuGet 包管理器”>“包管理器控制台”

  • 运行以下命令创建 SecondDbContext 的迁移:

    Add-Migration InitialCreate -Context SecondDbContext -OutputDir Migrations\SecondDbContextMigrations
    Update-Database -Context SecondDbContext
  • 至此,项目的目录结构如下:

  • 数据库如下:

需要注意的情况

请避免两个 DBContext 内的实体有互相主外键连接的情况

  • 示例

    // FirstDbContext
    public class FirstDbContext : DbContext
    {
    public FirstDbContext(DbContextOptions<FirstDbContext> options)
    : base(options)
    { } public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
    } public class Blog
    {
    public int BlogId { get; set; }
    public string Url { get; set; } public ICollection<Post> Posts { get; set; } public int StudentId { get; set; }
    public Student Student { get; set; }
    } public class Post
    {
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; } public int BlogId { get; set; }
    public Blog Blog { get; set; }
    } // SecondDbContext
    public class SecondDbContext : DbContext
    {
    public SecondDbContext(DbContextOptions<SecondDbContext> options)
    : base(options)
    { } public DbSet<Student> Students { get; set; }
    } public class Student
    {
    public int Id { get; set; }
    public string Name { get; set; } public ICollection<Blog> Blogs { get; set; }
    }

EF Core 2.2 对多个 DbContext 单个数据库的情况进行迁移的示例的更多相关文章

  1. EF Core 2.2 对多个 DbContext 多个数据库的情况进行迁移的示例

    目录 场景 创建新项目 创建第一个模型 创建第二个模型 使用依赖注入注册上下文 创建数据库 场景 在一个项目中,使用了多个 DbContext 且每个 DbContext 对应一个数据库的情况 创建新 ...

  2. EF Core 快速上手——创建应用的DbContext

    系列文章 EF Core 快速上手--EF Core 入门 EF Core 快速上手--EF Core的三种主要关系类型 本节导航 定义应用的DbContext 创建DbContext的一个实例 创建 ...

  3. [.NET Core] - 使用 EF Core 的 Scaffold-DbContext 脚手架命令创建 DbContext

    Scaffold-DbContext 命令 参数 Scaffold-DbContext [-Connection] <String> [-Provider] <String> ...

  4. [翻译 EF Core in Action 1.7] MyFirstEfCoreApp访问的数据库

    Entity Framework Core in Action Entityframework Core in action是 Jon P smith 所著的关于Entityframework Cor ...

  5. EF Core使用CodeFirst在MySql中创建新数据库以及已有的Mysql数据库如何使用DB First生成域模型

    官方教程:https://docs.microsoft.com/en-us/aspnet/core/data/?view=aspnetcore-2.1 使用EF CodeFirst在MySql中创建新 ...

  6. 第三节:EF Core上下文DbContext相关配置和生命周期

    一. 配置相关 1. 数据库连接字符串的写法 (1).账号密码:Server=localhost;Database=EFDB01;User ID=sa;Password=123456; (2).win ...

  7. EF Core 2.0 新特性

    前言 目前 EF Core 的最新版本为 2.0.0-priview1-final,所以本篇文章主要是针对此版本的一些说明. 注意:如果你要在Visual Studio 中使用 .NET Core 2 ...

  8. asp.net core系列 30 EF管理数据库架构--必备知识 迁移

    一.管理数据库架构概述 EF Core 提供两种主要方法来保持 EF Core 模型和数据库架构同步.一是以 EF Core 模型为基准,二是以数据库为基准. (1)如果希望以 EF Core 模型为 ...

  9. EF Core使用笔记(基于MySql数据库)

    一.什么是EF Entity Framework 是适用于.NET 的对象关系映射程序 (O/RM). 二.比较 EF Core 和 EF6 1.Entity Framework 6 Entity F ...

随机推荐

  1. 【学习笔记】TensorFlow

    1. tf.Graph().as_default() 的作用 首先看官网上的解释: 再看博主 Joanna-In-Hdu&Hust 对此比较通俗易懂的解释(https://www.cnblog ...

  2. Atcoder刷题小记

    1. 2019.4.27 agc016d 一道很坑的题. 首先判无解,求出异或值后排个序就可以. 然后直接让\(a_i\rightarrow b_i\)并查集维护,注意离散化和判重,答案加上联通块个数 ...

  3. git合并常见冲突

    如果一个文件在服务器上已经做了修改,然后在本地开发中又做了一些修改的时候,再发布这个文件时很容易造成代码冲突,错误如下, error: Your local changes to the follow ...

  4. Python的安装与小程序的编写

    Python的安装 在此之前,我完全不了解Python,为了完成任务,在慌忙之中了解了一下Python,通过百度,一步步安装好Python 过程 1.从官网中找到下载菜单并下载最新版本 2.双击pyt ...

  5. DirectX11 With Windows SDK--23 立方体映射:动态天空盒的实现

    前言 上一章的静态天空盒已经可以满足绝大部分日常使用了.但对于自带反射/折射属性的物体来说,它需要依赖天空盒进行绘制,但静态天空盒并不会记录周边的物体,更不用说正在其周围运动的物体了.因此我们需要在运 ...

  6. python 基础部分重点复习整理2

    把这里的题目争取刷一遍 博客记录 python的ORM框架peewee SQLAlchemy psycopg2 Django 在1 的基础上,重点突出自己以前没注意的,做到精而不杂!!! Python ...

  7. vue全局变量的使用

    新建一个VUE文件,声明一个变量,并且把它export. 在main.js中引入,并声明. 在其他地方使用,直接this就可以了.

  8. Java 集合系列08之 List总结

    一.List概述 1. List是一个接口,它继承于Collection接口,代表有序集合 2. ArrayList, LinkedList, Vector, Stack是List的4个实现类. Ar ...

  9. SVN的安装与使用教程

    转载:http://www.cnblogs.com/armyfai/p/3985660.html SVN简介: 为什么要使用SVN? 程序员在编写程序的过程中,每个程序员都会生成很多不同的版本,这就需 ...

  10. 你真的了解word-wrap和word-break的区别吗?

    这两个东西是什么,我相信至今还有很多人搞不清,只会死记硬背的写一个word-wrap:break-word;word-break:break-all;这样的东西来强制断句,又或者是因为这两个东西实在是 ...