1、设置好数据库连接字串
 
在项目中,找到 app.config(没有则在项目根目录手动新增,这里的设置只对本项目有效,不会影响到 Web 项目中的设置)。配置 <connectionStrings> 节点,新增 <add name="MyDBConnectString" providerName="System.Data.SqlClient" connectionString="datasource=.;initial catalog=MyDB;user id=sa;password=123456"/> ,Mvc4DAL 用的是名称 MyDBConnectString 的连接字串
 
publicclassSchoolContext : DbContext
 
{
 
publicSchoolContext() : base("name=MyDBConnectString")
 
若没有设置好连接字串,或是字串设置有误,将出现如下提示:
Anerror occurred while getting provider information from the database. This canbe caused by Entity Framework using an incorrect connection string. Check theinner exceptions for details and ensure that the connection string is correct.
 
 
 
2、运行命令Enable-Migrations
 
出现如下提示时,你需要执行 Enable-Migrations:
Enable-Migrations -ProjectName ST.DAL

ST.DAL为所在的项目

执行 Enable-Migrations 时可能会因为错误而打断,此时需要再次运行加参数的命令Enable-Migrations -Force:
Migrationshave already been enabled in project 'Mvc4DAL'. To overwrite the existingmigrations configuration, use the -Force parameter.
 
注意“Enable-Migrations”中间没有空格,“-Force”前面必须要有空格。
 
 
 
3、设置 AutomaticMigrationsEnabled为 true   
 
打开Migrations文件夹中的 Configuration.cs,AutomaticMigrationsEnabled默认为 false 改为 true就哦了,否则将出现提示:
Unable to update database to match the current model because there arepending changes and automatic migration is disabled. Either write the pendingmodel changes to a code-based migration or enable automatic migration. SetDbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enableautomatic migration. You can use the Add-Migration command to write the pendingmodel changes to a code-based migration.
 
 
 
四、最后执行 Update-Database
 
上述步骤都设置好了,打开“程序包管理器控制台”,运行命令 Update-Database,没有出错就大功成。这里要注意的是,数据库中有个名称为dbo.__MigrationHistory 的Table很重要,记录的是从创建数据库开始的全部更新的记录,所以在你没有绝对把握的情况下千万别动它。