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

1.开发环境中修改模型,在DbContext中加入静态构造函数,并设置初始化模式:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

staticDemoDbContext()

{

Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

}

View Code

如果是Mysql,需要在DbContext加上 [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 属性,否则操作数据库时会报错,更改结束后,注释掉就可以了

新增类时需要在DbContext添加该类的引用属性,如:新增Department类:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public DbSet Departments { get; set; }

View Code

2.生成环境中数据迁移

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

2.2 修改DbContext静态构造函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

staticDemoDbContext()

{

Database.SetInitializer(null);

}

View Code

2.3 在程序包管理器控制台,执行语句:

PM> Enable-Migrations -EnableAutomaticMigrations

这时会在工程下建立文件夹:Migrations 和 Configuration.cs 文件

40a7491271383039fe2ce7d96c3c8aca.png

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

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类:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

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类中引用实例

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

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表已经添加

151bb49a2de9278548d84917a40b5584.png

3. 参考资料

4.源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值