多个Context单个数据库如何进行迁移

第一个Context

    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; }
    }

第二个Context

    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; }
    }

configservice中注入

    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=Db;UserId=账号;Password=密码;"; 
        services.AddDbContext<FirstDbContext> (options => options.UseSqlServer(connection)); 
        services.AddDbContext<SecondDbContext>(options => options.UseSqlServer(connection));
    }

迁移命令

FirstDbContext

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

SecondDbContext

  1. Add
Add-Migration InitialCreate -Context SecondDbContext  -OutputDir Migrations\SecondDbContextMigrations
  1. update
Update-Database -Context SecondDbContext 

需要注意的情况

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

posted @ 2020-02-11 19:22  Jonny-Xhl  阅读(212)  评论(0编辑  收藏  举报