如何在asp.net mvc 3.0使用Nuget更新数据库?
广告:
asp.net mvc3.0我们就需要更新数据库,方法是:
1.安装VS的Nuget。打开Nuget控制台,输入Enable-Migrations启用数据库迁移。如果已经启用,控制台会提示“Migrations have already been enabled in project '***'. To overwrite the existing migrations configuration, use the -Force parameter.”
2.标记迁移点,输入Add-Migration ***,星号为迁移点名称,可自定义。
3.输入Update-Database完成更新。
此时再执行程序,则不会再出现报错,数据库也更新完毕了。如果想回退到某一次的迁移点,只需要在Nuget控制台中输入 Update-Database –TargetMigration:"***" 星号为迁移点名称。另外可以通过Script参数生成脚本,例如Update-Database -Script -SourceMigration:"**" -TargetMigration:"**" 这样就会生成一个sql脚本而不是直接更新数据库。
当然,如果觉得操作控制台的指令太多不方便,可以使用自动迁移功能。方法如下:
1.打开 Migrations文件夹下的Configuration.cs,修改代码为
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
2.如果需要更新数据库,只需要在Nuget控制台输入Update-Database -Verbose即可,如果提示“Automatic migration was not applied because it would result in data loss”(不能自动迁移,会导致数据丢失) ,则在Update-Database 后面加 -Force参数即可。注意,这样并不会引起数据丢失。
PM> Update-Database -Force
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No migrations configuration type was found in the assembly 'TopWin.Etone.Web'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
广告: