使用db-migration更新数据库时如何避免数据丢失?

4

当我使用数据库迁移更新数据库时,遇到了一个问题:

Automatic migration was not applied because it would result in data loss.

我使用了 System.ComponentModel.DataAnnotations,例如 [Required][StringLength(25)] 来修饰一些属性。比如说 Title 属性。

我知道如果我将 AutomaticMigrationDataLossAllowed 设置为 true 并执行 Update-Database -Force,我的数据库将会被更新但是数据也将被删除,我想要保护我的数据。

我使用的是 Entity Framework 6.x。

我该如何解决这个问题?

配置类:

namespace Jahan.Blog.Web.Mvc.Migrations
{
   using System;
   using System.Data.Entity;
   using System.Data.Entity.Migrations;
   using System.Linq;

   internal sealed class Configuration 
    : DbMigrationsConfiguration<Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext>
   {
       public Configuration()
       {
           AutomaticMigrationsEnabled = true;
           AutomaticMigrationDataLossAllowed = false;
       }

       protected override void Seed(Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext context)
       {

       }
   }
}

初始类:

namespace Jahan.Blog.Web.Mvc.Migrations
{
   using System;
   using System.Data.Entity.Migrations;

   public partial class Initial : DbMigration
   {
       public override void Up()
       {
       }

       public override void Down()
       {
       }
   }
}

我的DbContext:

namespace Jahan.Blog.DataAccess
{
   public class JahanBlogDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole,    UserClaim>
   {
       public JahanBlogDbContext()
           : base("name=JahanBlogDbConnectionString")
       {

       }
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Comment>().HasRequired(t => t.Article).WithMany(t => t.Comments).HasForeignKey(d => d.ArticleId).WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
       }
       // ... codes ....
   }
}
1个回答

3

您可以添加 SQL 语句来修复数据,以使其符合您的需求。您需要确保由 EF 生成的 alter 语句不会导致数据丢失。

在迁移中使用 Sql 方法可运行自己的 SQL 语句:

public override void Up()
{
    //Add this to your migration...
    Sql("UPDATE dbo.Table SET Name = LEFT(Name, 25) WHERE LEN(Name) > 25")

    //...before the code generated by EF
    AlterColumn("dbo.Table", "Name ", c => c.String(nullable: false, maxLength: 25));
}

请明确告知我应该在哪个文件中添加这段代码? - x19
1
当您对 Model 进行更改之后, 您应将此代码放置在添加迁移时生成的迁移文件的 Up 方法中。http://msdn.microsoft.com/en-gb/data/jj591621 - Colin
你的评论很有用,我的数据库已经更新。(我在SqlServer中看到了数据库,一切正常)但是当程序运行时,我遇到了一个错误......'JahanBlogDbContext'上下文的模型与创建数据库时不同。考虑使用Code First Migrations来更新数据库(http://go.microsoft.com/fwlink/?LinkId=238269)。 - x19
我从数据库中删除了 __MigrationHistory 表的记录。现在我的程序成功运行了! - x19
如果我想通过使用db-migration确定数据库字段的值范围,应该怎么做? - x19

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接