做mvc+EF的项目中如果你用的是code first,当更改某实体类时,你会发现数据库中的数据没了,该怎么做?

来源:互联网 发布:淘宝店铺监控多久解除 编辑:程序博客网 时间:2024/04/29 08:52
工具 -> 库程序包管理器 -> 程序包管理器控制台
运行命令 Enable-Migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201212090821166_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.

会出现,上面这个错误。不用管它,这时候,你会发现在程序端多出一个文件夹叫Migrations
这里面有一个Configuration.cs文件
打开它,然后修改成如下样子,
public Configuration()
{
AutomaticMigrationsEnabled = true; //这里变成true
ContextKey = "codefirst.DAL.BaseContext";//codefirst.DAL.BaseContext为你的BaseContext的命名空间
}

修改完成后,运行
Update-Database -Force这个时候,你再看一下数据库里面的表结构是不是变了,而数据却没有丢呢.

以后再有更改,只要保证Configuration.cs文件中的AutomaticMigrationsEnabled = true;
只运行Update-Database -Force就可以了
0 0