How to change the column type in table using Entity Framework core - entity-framework-core

Hi I created my database using Entity Framework core with code first approach. Now there is a change in the column type from int to varchar/string? I can change the column from the database itself but my understanding is that it won't be a good idea and would create issues. I searched through but I didn't get my answer on the net for Entity framework core.

You should use EF Core migrations to update your db schema. The documentation is pretty good, so make sure to go through it.
However, this is a summary of how the process would be:
Make the change in your model (which by convention will be automatically detected. Alternatively, use the Fluent API in your DB Context OnCreate method or in your EntityConfigurations).
Add a migration running the following CLI command : dotnet ef migrations add SomeDescriptiveNameAboutWhatThisMigrationWillDo.
A migration file with an Up and Down method will be automatically generated. The Up will be run when you apply the migration, and the Down if you ever decide to revert it . You could add changes to the automatically scaffolded migration file. Based on the code in the migration file, EF Core will then generate a SQL script and apply the changes to the DB.
Once you have added (and maybe edited) the migration file, you need to apply it to the DB. You do that by running dotnet ef migrations update.
EF Core tracks all applied migrations in a table in your DB called by default __EFMigrationsHistory
In your particular case of changing a column type, EF Core might try to drop the column and recreate it, which will result in data loss. If you wanna keep your data, I would recommend altering the migration script to actually split the process in two: first add a new column with the new type and a slightly different name, then write some custom SQL to migrate data from the old column to the new one, then delete the old column and finally rename the new column to the correct name. To be honest, I am not sure if there is some custom migration operation that will out of the box change the data type without data loss, there might be.
To double check if the migration will generate data loss or check if it will do what you expect it to do, you can generate the SQL script that will be used by running dotnet ef migrations script <from migration> <to migration>. After reviewing it, you can either copy/paste and run the script in your DB, or just run the command detailed in step 4 above.

You can modify your database schema to match your domain model with the add-migration command.
After changing the type of the property on your c# class from int to string, simply run
add-migration <SomeDescriptiveName>
After the creation of the migration files, you can apply them with the update-database command.
You can read more about migrations here.

Related

EF Core Migrations manual edits possible?

I am using EF Core 2.0 in my sample project with some value object configurations. I modify the code and generate migrations via CLI command line. In the last migration rather than adding a new database table as it should, it is trying to rename existing tables to each other and create an extra table for existing one. I could not figure out the reason for it.
Issue is, since with EF Core the snapshot is a separate auto-generated file from the migration itself I don't want to modify the snapshot.
I only want to modify the migration script so that it will not rename multiple tables, and then generate the snapshot from the migrations I created.
I did not see any command for this in the CLI - is it such a bad practice to modify the scaffolded migration and regenerate or am I missing some obvious new link where how to manually modify migration scripts is explained?
Thanks a bunch.
Update 1: After comments, added info about the snapshot from this link.
Because the current database schema is represented in code, EF Core doesn't have to interact with the database to create migrations. When you add a migration, EF determines what changed by comparing the data model to the snapshot file. EF interacts with the database only when it has to update the database. +
I examined my generated snapshot code from source control. It exactly has added one extra table as what I needed.
The migration script to generate this is hectic at best - renaming multiple tables to each other and then warning that this could break causing multiple issues.
Since this is a sample project for me with only mock data as of now at least, I decided to go for it and not break the automated scripts. I am willing to lose some mock data at this stage rather than wasting time on it.
If this were in a production database I would be extremely careful to manually create the same result with intervention modifying both the scaffold and the migration file.
I am accepting this one as an answer (basically saying current EF Core does not support it to the best of my current knowledge) since there is no other candidate now - I will be more than glad to accept if any better answer shows up.

EF migrations won't recognize existing tables

I've set up this project from DB first and everything went fine. I can debug properly. But when I try make a change to one of my models, instead of the new migration showing a simple AlterColumn statement, it keeps trying to reinitialize the entire database.
I've tried running update database -script and only inserting the _MigrationHistory table record. Even after that, it still wants to create all the tables.
Has this ever happened to anyone?
When you start with an existing database you need to do an empty (no-op) migration to set a baseline. This is because EF will use the model in the prior migration to compare, so if there is not one (in code) you get all your database objects. Inserting a record into __MigrationHistory just tells EF the code migration has been applied - it doesn't use it for the compare.
enable-migrations
add-migration MyBaseline -IgnoreChanges // no Up() code, but model saved
update-database
// Now I can change my model and generate a migration with difference
See here.

EF 6.1.3 automatic migrations

I created an initial migration into my database when I executed a database operation via code first.
All the tables got created successfully.
I have successfully enabled automatic migrations.
I've added a couple of columns to a model.
When I run the "Update-Database –Verbose", I get an error message (which I understand, but don't now why it's coming out) of "There is already an object named 'Categories' in the database."
The Categories table along with all the rest of the tables got created on the initial migration (as explained above).
I made a change (adding the two other columns) to another model (Customer).
I would think, that the Code First migration would simply look at the entire DBSet model, determine what changed, then simply apply the necessary SQL. Instead, it's trying to create the Categories table again which already exists.
Can someone please explain to me how I can simply update the DB without this happening? What am I doing wrong or what do I need to do in order to get it to work....
EDIT
Successful creation of EF code-first Migrations setup:
Enable-Migrations -EnableAutomaticMigrations
Add-Migration Initial (Creates _Initial.cs file).
Comment out code in _Initial.cs file within Migrations folder for
code that you don't want to execute AFTER initial DB run to create tables.
Set Configuration.cs file to Public access
Add following code in Global.asax file
Database.SetInitializer(new
MigrateDatabaseToLatestVersion());
Update-Database - Verbose (for any DB changes)
Set "AutomaticMigrationDataLossAllowed = true;" in Configuration.cs
file within Migrations folder. (for any DB changes)

Update model snapshot of last migration in Entity Framework and reapplying it

I'm using EF6 code-first migrations for existing database but initial DbContext does not fully cover existing schema (since it's massive). So from time to time I have to make updates to the model in database-first style. For example when I need an entity mapping for a table or a column that is already in the database but not reflected in the code I do the following:
Make all change (add new entity, rename the column mapping or add new property)
Scaffold migration representing the latest model snapshot stub_migration
Copy-paste latest serialized model from stub_migration to the last_migration resource file
Delete stub_migration
Revert last_migration in database
Update-Database so that model snapshot in [__MigrationHistory] table would be also updated
I understand that this aproach is a bit hackish and the proper way would be to leave empty stub_migration but this would force lots of empty migrations which I would rather avoid.
Looking at a similar scenario from MSDN article (Option 2: Update the model snapshot in the last migration) I wouldn't imagine that there is an easier way rather than writing power shell script, managed code or both to make it work. But I would rather ask community first before diving deep into it.
So I wonder: is there a simple way to automate generation of new model snapshot in latest migration and reaplying it?
I'm doing something similar. I have a large database and I am using the EF Tools for VS 2013 to reverse engineer it in small parts into my DEV environment. The tool creates my POCOs and Context changes in a separate folder. I move them to my data project, create a fluent configuration and then apply a migration (or turn automigration on).
After a while I want a single migration for TEST or PROD so I roll them up into a single migration using the technique explained here: http://cpratt.co/migrating-production-database-with-entity-framework-code-first/#at_pco=smlwn-1.0&at_si=54ad5c7b61c48943&at_ab=per-12&at_pos=0&at_tot=1
You can simplify the steps for updating DbContext snapshot of the last migration applied to database by re-scaffolding it with Entity Framework:
Revert the last migration if it is applied to the database:
Update-Database -Target:Previous_Migraton
Re-scaffold the last migration Add-Migration The_name_of_the_last_migration which will recreate the last migrations *.resx and *.Designer.cs (not the migration code), which is quite handy.
Those 2 steps are covering 4 steps (2-5) from original question.
You can also get different bahavior depending on what you want by specifying the flags -IgnoreChanges and (or) -Force
And by the way, the major problem with the updating the DbContext snapshot is not how to automate those steps, but how to conditionally apply them to TEST/PROD environments depending on whether you actually want to suppress the warning because you've mapped existing DB-first entities in you DbContext or you want it it to fail the build in case you've created new entities and forgot to create a code-first migration for them.
So, try to avoid those steps altogether and maybe create empty migrations when you just want to map existing tables to your code.

Entity Framework adds "RenameTable" command when scaffolding migration

I have changed my model and is scaffolding a new migration using the Add-Migration package manager command.
However, for some reason, EF think that I have been renaming an object for one of my classes. The class names are similar in name and have similar properties and relationships.
The problem is that the Update-Database command fails because of the rename. The very first command is RenameTable() and later on the migration tries to delete an index on the table that has been renamed (and doesn't exist anymore).
I would like to force EF to scaffold a migration where the old table is dropped and a new one is created instead. How do I achieve this? My impression was that EF can't be "smart" when figuring out renames and should always drop tables that are no longer mapped to an entity.