在项目开发中,难免会遇到数据库表结构变化的情况,手动去维护数据库是一件繁琐的事情。好在EntityFramwork为我们这些懒人提供了可供自动更新数据结构的机制,废话不多说,直接上代码:

 

  首先创建一个Configuration类,继承自DbMigrationsConfiguration

public sealed class Configuration : DbMigrationsConfiguration<MyContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }

  其次我们再添加一个初始化DB的类,继承于MigrateDatabaseToLatestVersion

public class InitDb: MigrateDatabaseToLatestVersion<MyContext,Configuration>
    {
    }

  最后在我们的DbContext的构造函数中直接调用InitDb即可

public class MyContext:DbContext
    {
        public SnailContext()
        {
            Database.SetInitializer(new InitDb());
        }
        
        //....
    }

  

相关文章:

  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
  • 2021-05-06
  • 2022-12-23
  • 2021-12-14
  • 2021-11-13
  • 2022-01-17
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2021-07-10
相关资源
相似解决方案