When I was making update my database by using db-migration, I faced a problem that was
Automatic migration was not applied because it would result in data loss.
(I used System.ComponentModel.DataAnnotations
such as [Required]
and [StringLength(25)]
for some properties. For example Title
property.)
I know if I set the AutomaticMigrationDataLossAllowed
to true
and Update-Database -Force
, my database will be update but my data will be removed and I'm going to prevent from it. I want to protect my data.
I've used Entity Framework 6.x
How can I solve this problem?
Configuration class:
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)
{
}
}
}
Initial class:
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()
{
}
}
}
My 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 ....
}
}
You can add sql to fix the data in a way that is acceptable to you. You need to ensure that the alter statements generated BY EF do not cause data loss.
Use the Sql
method in a migration to run your own 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));
}