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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 人文社科 > 生活经验 >内容正文

生活经验

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

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

1.開(kāi)發(fā)環(huán)境中修改模型,在DbContext中加入靜態(tài)構(gòu)造函數(shù),并設(shè)置初始化模式:

staticDemoDbContext()

{

Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

}

View Code

如果是Mysql,需要在DbContext加上?[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 屬性,否則操作數(shù)據(jù)庫(kù)時(shí)會(huì)報(bào)錯(cuò),更改結(jié)束后,注釋掉就可以了

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

public DbSet Departments { get; set; }

View Code

2.生成環(huán)境中數(shù)據(jù)遷移

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

2.2 修改DbContext靜態(tài)構(gòu)造函數(shù):

staticDemoDbContext()

{

Database.SetInitializer(null);

}

View Code

2.3?在程序包管理器控制臺(tái),執(zhí)行語(yǔ)句:

PM> Enable-Migrations -EnableAutomaticMigrations

這時(shí)會(huì)在工程下建立文件夾: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 執(zhí)行語(yǔ)句:(為測(cè)試效果,刪除了Student類中的Email和Score屬性)

PM> Add-Migration InitialCreate

此時(shí)會(huì)自動(dòng)生成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 執(zhí)行語(yǔ)句:Update-Database -Verbose 更改即應(yīng)用到數(shù)據(jù)庫(kù)中

2.6 新增類(表)

2.6.1 新增類 City,并在DbContext類中引用實(shí)例

public classCity

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

}

View Code

2.6.2 執(zhí)行語(yǔ)句

PM> Add-Migration AddCity

2.6.3 執(zhí)行語(yǔ)句

PM> Update-Database -Verbose

查看數(shù)據(jù),City表已經(jīng)添加

3. 參考資料

4.源碼

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。