Entity Framework - Code first

2

When I work with EF code first, precisely when the tables already created have data and I need to create a new field or delete a new field. EF forces me to delete the data I had in the tables in order to add or remove a new field to a table.

If you have an application already developed with EF and the tables in the database already have information and maintenance is needed. How to handle this type of problems?

    
asked by Pedro Ávila 20.12.2016 в 18:57
source

3 answers

1

You have two options or use migrations , or pass initializers and modify the database to "hair".

There is nothing else to do, I am currently developing an application with code first, although for the time being I have not put it into production. My idea for the future is to use migrations, that if avoiding that the application applies the changes directly on the basis of data, the idea is to capture the resulting SQL to apply it by hand, I think that in this way I will have more control over the migration (Update-database -Script).

Greetings,

    
answered by 21.12.2016 в 13:32
0

The process is quite long and depends on what you want to add.

Here is all the information

To summarize, you must enable your application to migrate, this will generate a migrations class that you can customize if you wish.

Also if you modify your code, by executing a command you can make the application itself try to add the necessary classes for the migration. However, it is always good to review the migration, because in some cases it may not be optimal what you leave.

    
answered by 20.12.2016 в 19:06
0

What I do is add the fields in the BD and then add them to the models.

To avoid losing information in the DB by adding the fields you accept null or have a default value.

Example:

alter table AlumnosSet
add Apellidos  nvarchar(300) not null  DEFAULT '',
    FechaBaja  datetime null    -- Acepta nulos

I print the values, taking only the name field currently

Then I add the fields to the model with the wizard it's easy:

The table was updated:

The data in the BD:

Example in console:

In this way I would solve it, another way is to eliminate the model and recreate it but now with the option EF Designer from database , much easier than doing integrations.

    
answered by 20.12.2016 в 20:38