EF Code 6 Early migrations prevent or prevent disruptive updates

Question: Is there a setting for unintentional data loss when executing a script migration.

I use the first code migrations from 4.1, but while experimenting in a test project, I came across behavior that I did not expect. Maybe I did not take advantage of the new features.

Let's say I have a simple model:

public class Customer { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string City { get; set; } } 

and context:

  public class CustContext : DbContext { public CustContext() : base("DefaultConnection") { } public DbSet<Customer> Customers { get; set; } } 

I have already enabled migrations, created an initial migration, updated the database as follows, and then populated the table with data.

 enable-migrations add-migration initial update-database 

Then I changed the name Address to HomeAddress. This is a migration script:

 add-migration HomeAddress public partial class HomeAddress : DbMigration { public override void Up() { AddColumn("dbo.Customers", "HomeAddress", c => c.String()); DropColumn("dbo.Customers", "Address"); } public override void Down() { AddColumn("dbo.Customers", "Address", c => c.String()); DropColumn("dbo.Customers", "HomeAddress"); } } 

This is the configuration script:

  internal sealed class Configuration : DbMigrationsConfiguration<CodeFirstMigrations.Model1.CustContext> { public Configuration() { AutomaticMigrationsEnabled = false; AutomaticMigrationDataLossAllowed = false; } protected override void Seed(CodeFirstMigrations.Model1.CustContext context) { } } 

When I ran the update-database command, I fully expected to get an error in the line β€œfailed to complete the migration because it will lead to data loss ...” I really see that this error works a lot on my own project.

But instead, he happily dropped the (filled) address column and created a new HomeAddress column.

I decided that there must be a configuration parameter to control this behavior, but all I could find was AutomaticMigrationDataLossAllowed , which apparently only applies to automatic transitions.

Did I miss something?

+5
source share
2 answers

This has been raised as a problem already, but rejected as "by design."

This is solved by design - we only warn about automatic permutations with data loss.

Look at the error here .

+4
source

You can use:

 public partial class HomeAddress : DbMigration { public override void Up() { AddColumn("dbo.Customers", "HomeAddress", c => c.String()); Sql("UPDATE "dbo.Customers" SET HomeAddress = Address"); DropColumn("dbo.Customers", "Address"); } public override void Down() { AddColumn("dbo.Customers", "Address", c => c.String()); DropColumn("dbo.Customers", "HomeAddress"); } } 

Then you save your data.

0
source

Source: https://habr.com/ru/post/1206461/


All Articles