让EntityFramwork自动更新表结构
在项目开发中,难免会遇到数据库表结构变化的情况,手动去维护数据库是一件繁琐的事情。好在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());
}
//....
}

浙公网安备 33010602011771号