• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Code First Migrations更新数据库结构(数据迁移)

mysql 搞代码 4年前 (2022-01-09) 54次浏览 已收录 0个评论

背景 code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化更新后,原数据将全部丢失,故我们可以引入EF的数据

背景

code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化本文来源gaodai#ma#com搞@@代~&码网更新后,原数据将全部丢失,故我们可以引入EF的数据迁移功能来完成。

要求

  1. 已安装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%20if%20the%20context%20targets%20an%20existing%20database…
Detected%20database%20created%20with%20a%20database%20initializer.%20Scaffolded%20migration%20’201212090821166_InitialCreate’%20corresponding%20to%20existing%20database.%20To%20use%20an%20automatic%20migration%20instead,%20delete%20the%20Migrations%20folder%20and%20re-run%20Enable-Migrations%20specifying%20the%20-EnableAutomaticMigrations%20parameter.
Code%20First%20Migrations%20enabled%20for%20project%20MvcApplication1.

此时项目会出现如下文件夹:

打开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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Code First Migrations更新数据库结构(数据迁移)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址