mvc模型中MySQL类_Mvc5 EF6 CodeFirst Mysql (二) 修改数据模型
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)題。
- 上一篇: 淮南市办个挖掘机证要多少钱?
- 下一篇: 安全帽多少钱啊?