zoukankan      html  css  js  c++  java
  • 多个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 MigrationsFirstDbContextMigrations
    
    1. update
    Update-Database -Context FirstDbContext
    

    SecondDbContext

    1. Add
    Add-Migration InitialCreate -Context SecondDbContext  -OutputDir MigrationsSecondDbContextMigrations
    
    1. update
    Update-Database -Context SecondDbContext 
    

    需要注意的情况

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

  • 相关阅读:
    为什么叫"鲁棒"图
    Linux系统信息查看命令......
    網頁配色工具
    java基础方面知识点
    網頁設計收藏站70個
    bj_linux...
    工具
    软件工程阅读(中英文对照)之软件维护
    软件工程新方法和技术简介(英文)
    软件工程阅读(中英文对照)之文档技术
  • 原文地址:https://www.cnblogs.com/cqxhl/p/12993288.html
Copyright © 2011-2022 走看看