Doubt on automatic Migration with MigrateDatabaseToLatestVersion

2

With automatic migration is the database updated also when some property is excluded from my model class? That is, besides adding a new attribute if something is added to my class, does it also remove it? Like the example below, I'm trying to get it to remove the zip code field it was adding and it's empty, but that's not happening. Returns an AutomaticDataLossException exception

Top

static void Main(string[] args)
{
    Aluno aluno = new Aluno
    {
        AlunoId = 1,
        Nome = "Cláudia",
        Email = "[email protected]"
    };

    using (var db = new DBContexto())
    {
        db.Aluno.Add(aluno);
        db.SaveChanges();
    }
}

Model Class

public class Aluno
{
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
    //public string Cep { get; set; }
}

Context

public class DBContexto : DbContext
{
    public DBContexto()
        : base(@"data source=(local); initial catalog=DbAluno; integrated security=true;")
    {
        Database.SetInitializer<DBContexto>(new MigrateDatabaseToLatestVersion<DBContexto, Configuration>());
    }
    public DbSet<Aluno> Aluno { get; set; }
}

Configuration

public class Configuration : DbMigrationsConfiguration<ConsoleApplication1.DBContexto>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(ConsoleApplication1.DBContexto context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}
    
asked by anonymous 17.09.2015 / 01:56

1 answer

2
  

With automatic migration is the database updated also when some property is excluded from my model class? That is, in addition to adding a new attribute if something is added to my class, does it also remove?

Yes. The column is deleted.

  

As the example below, I'm trying to get it to remove the zip code field that was adding and is empty, but this is not happening. Returns a AutomaticDataLossException exception.

Yes, this is a protection of the Entity Framework so that important data is not lost. It is turned on by default.

Since you are in a development environment, you can include the following in the Migrations configuration to avoid this scan:

internal sealed class Configuration : DbMigrationsConfiguration<MeuProjetoContext>
{
    public Configuration()
    {
        AutomaticMigrationDataLossAllowed = true;
    }

    ...
}
    
17.09.2015 / 02:08