Code First Migrations更新数据库结构(数据迁移)
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-PC\SQLEXPRESS" providerName="System.Data.SqlClient" />
- </connectionStrings>
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
数据库中的原数据也没有丢失!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2013-10-20 os 下载地址