關於EF自動生成數據庫

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很重要,記錄的是從創建數據庫開始的全部更新的記錄,所以在你沒有絕對把握的情況下千萬別動它。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章