Link to home
Start Free TrialLog in
Avatar of Member_2_8198376
Member_2_8198376

asked on

Adding a column to Sql Server with Entity Framework without dropping data

I've inherited a .NET Framework app with entity framework that uses code first to a SQL Server db.
I need to add a column to the table without destroying any of the old data.
I tried changing the code to insert into a new column and added a column manually, but I got a message stating that I had to add a column through code-first migration. (I'm new to Entity Framework.)
I read in a Microsoft Site that it is possible to modify the schema to keep the data:
"Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script."
I don't know if that is the only way to keep the data, or if there is a way to do that with Code First Migration. I also don't know which is easier or the advantages/disadvantages of either way. I've already made the change to the Model file.
Is there a way that I can change the connection string so that it recreates the database locally so that I can test it out?
Will the Package Manager Console command, "add-migration nameOfFile" drop any data?
If I change the existing schema, do I need to do anything else for Entity Framework to recognize the change?
thanks
Avatar of Pushpakumara Mahagamage
Pushpakumara Mahagamage
Flag of Sri Lanka image

What's the output to your alter table script

ALTER TABLE table name ADD colmn name  DATATYPE
Avatar of Member_2_8198376
Member_2_8198376

ASKER

Hello Pushpakumara Mahagamage
   Do I do that command in the Nuget Package Manager Console?
   After I updated my Model class, I went to the Nuget Package Manager Console and I put:
Enable-Migrations –EnableAutomaticMigrations
   Then, in the Nuget Package Manager Console and I put:
Update-Database
   That worked.
   .NET doesn't let me make changes directly to the database because the app was created Code First, unless there's some way that I don't know about.
   Is your command something I put in the Nuget Package Manager Console ?
thanks,
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.