CodeFirstMigrations更新数据库结构
作者:网络转载 发布时间:[ 2014/7/18 14:41:00 ] 推荐标签:数据开发 数据库
背景
code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化更新后,原数据将全部丢失,故我们可以引入EF的数据迁移功能来完成。
要求
已安装NuGet
过程示例
|
//原model
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Lesson {
public int lessonID { get; set; }
[Required]
[MaxLength(50)]
public string lessonName { get; set; }
[Required]
public string teacherName { get; set; }
public virtual UserInfo UserInfo{get;set;}
}
//新model
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Lesson {
public int lessonID { get; set; }
[Required]
[MaxLength(50)]
public string lessonName { get; set; }
[Required]
[MaxLength(10)]
public string teacherName { get; set; }
public virtual UserInfo UserInfo{get;set;}
}
|
注:区别在于,我们给teacherName属性加了一个长度限制。
接下来,我们将开始持久化此model至数据库中(我们现在只是对属性作修改,此时数据库中此字段的长度为nvarchar(max),并不是nvarchar(10))
1:在config中配置数据库连接:
<connectionStrings>
<add name="TestUsersDB" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestUsersDB;Data Source=XCL-PCSQLEXPRESS" providerName="System.Data.SqlClient" />
</connectionStrings>
2:打开NuGet控制台:


sales@spasvo.com