日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

mvc模型中MySQL类_Mvc5 EF6 CodeFirst Mysql (二) 修改数据模型

發布時間:2023/11/27 生活经验 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mvc模型中MySQL类_Mvc5 EF6 CodeFirst Mysql (二) 修改数据模型 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.開發環境中修改模型,在DbContext中加入靜態構造函數,并設置初始化模式:

staticDemoDbContext()

{

Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

}

View Code

如果是Mysql,需要在DbContext加上?[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 屬性,否則操作數據庫時會報錯,更改結束后,注釋掉就可以了

新增類時需要在DbContext添加該類的引用屬性,如:新增Department類:

public DbSet Departments { get; set; }

View Code

2.生成環境中數據遷移

2.1 首先安裝 Enitity Framework:Install-Package EntityFramework

2.2 修改DbContext靜態構造函數:

staticDemoDbContext()

{

Database.SetInitializer(null);

}

View Code

2.3?在程序包管理器控制臺,執行語句:

PM> Enable-Migrations -EnableAutomaticMigrations

這時會在工程下建立文件夾:Migrations 和?Configuration.cs 文件

internal sealed class Configuration : DbMigrationsConfiguration{publicConfiguration()

{

AutomaticMigrationsEnabled= true;

}protected override voidSeed(MvcDemo.DAL.DemoDbContext context)

{//This method will be called after migrating to the latest version.//You can use the DbSet.AddOrUpdate() helper extension method//to avoid creating duplicate seed data. E.g.//

//context.People.AddOrUpdate(//p => p.FullName,//new Person { FullName = "Andrew Peters" },//new Person { FullName = "Brice Lambson" },//new Person { FullName = "Rowan Miller" }//);//}

}

View Code

2.4 執行語句:(為測試效果,刪除了Student類中的Email和Score屬性)

PM> Add-Migration InitialCreate

此時會自動生成InitialCreate類:

usingSystem;usingSystem.Data.Entity.Migrations;public partial classInitialCreate : DbMigration

{public override voidUp()

{

DropColumn("dbo.Student", "Email");

DropColumn("dbo.Student", "Score");

}public override voidDown()

{

AddColumn("dbo.Student", "Score", c => c.Double(nullable: false));

AddColumn("dbo.Student", "Email", c => c.String(unicode: false));

}

}

View Code

2.5 執行語句:Update-Database -Verbose 更改即應用到數據庫中

2.6 新增類(表)

2.6.1 新增類 City,并在DbContext類中引用實例

public classCity

{public string ID { get; set; }public string Name { get; set; }

}

View Code

2.6.2 執行語句

PM> Add-Migration AddCity

2.6.3 執行語句

PM> Update-Database -Verbose

查看數據,City表已經添加

3. 參考資料

4.源碼

總結

以上是生活随笔為你收集整理的mvc模型中MySQL类_Mvc5 EF6 CodeFirst Mysql (二) 修改数据模型的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。