当我想使用db-migration更新数据库时如何防止数据丢失?

时间:2014-10-21 10:27:53

标签: database entity-framework entity-framework-6 database-migration

当我使用db-migration更新我的数据库时,我遇到了一个问题

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

(对于某些属性,我使用了System.ComponentModel.DataAnnotations,例如[Required][StringLength(25)]。例如Title属性。)

我知道如果我将AutomaticMigrationDataLossAllowed设置为trueUpdate-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 个答案:

答案 0 :(得分:3)

您可以添加sql以您可接受的方式修复数据。您需要确保BY 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));
}