没网站做推广,上传文件生成链接下载,分析网站建设流程,母婴网站建设背景 code first起初当修改model后#xff0c;要持久化至数据库中时#xff0c;总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges)#xff0c;此时就会产生一个问题#xff0c;当我们的旧数据库中包含一些测试数据时#xff0c;当持久化更新后#xff0c;…背景 code first起初当修改model后要持久化至数据库中时总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges)此时就会产生一个问题当我们的旧数据库中包含一些测试数据时当持久化更新后原数据将全部丢失故我们可以引入EF的数据背景code first起初当修改model后要持久化至数据库中时总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges)此时就会产生一个问题当我们的旧数据库中包含一些测试数据时当持久化更新后原数据将全部丢失故我们可以引入EF的数据迁移功能来完成。要求已安装NuGet过程示例//原modelusing 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;}}//新modelusing 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 -EnableAutomaticMigrationsparameter.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本文原创发布php中文网转载请注明出处感谢您的尊重