CodeFirstMigrations更新数据库结构(数据迁移)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了CodeFirstMigrations更新数据库结构(数据迁移),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2588字,纯文字阅读大概需要4分钟。
内容图文
![CodeFirstMigrations更新数据库结构(数据迁移)](/upload/InfoBanner/zyjiaocheng/530/30246e4ad8ea420fbd9bc83ea5d9d557.jpg)
背景 code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化更新后,原数据将全部丢失,故我们可以引入EF的数据
背景
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中配置数据库连接:
2:打开NuGet控制台:
3:运行命令Enable-Migrations
可能会出现如下错误:
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201212090821166_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations
parameter.
Code First Migrations enabled for project MvcApplication1.
此时项目会出现如下文件夹:
打开configuation.cs,将作出如下修改:
public Configuration() { AutomaticMigrationsEnabled = true; }
再次执行Update-Database:
因为我把长度从max改为10,在更新数据结构时,它认为此操作会导致数据丢失,如下:
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Applying automatic migration: 201212090848057_AutomaticMigration.
Automatic migration was not applied because it would result in data loss.
如果确保没事,只需给此命令加个强制执行的参数即可:
Enable-Migrations -Force
最后再次执行:Update-Database
数据库中的原数据也没有丢失!
3:
内容总结
以上是互联网集市为您收集整理的CodeFirstMigrations更新数据库结构(数据迁移)全部内容,希望文章能够帮你解决CodeFirstMigrations更新数据库结构(数据迁移)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。