I've already created a database using code first. It worked well. Many changes have since been made to the database outside Visual Studio. So many that any attempt at migration generates errors. So my question is, is there a way to switch a solution from code first to database first?
1 Answer
This should be easy, just create a new, database first model and delete your code first model. Most of your code will compile just fine if you are in the same namespace and take care of naming your context in the same way.
Switching to database first however, makes you lose the ability to migrate which is a solid advantage of the code first approach. If I were you, I would spend more time on trying to create a migration, even write one manually if the generator fails but still stick with the code first.
6 Comments
Heath
How do I do that? Do I add a ADO.NET Entity Data Model? If so, what happens to the models I've already created?
Wiktor Zychla
Do what? Create a database first model? Add/New item/Data/Entity framework model from existing database. It's just few clicks in VS. You probably ask for something else, though...
Santhos
@WiktorZychla Do you really thank that code first is appropriate for a middle-sized project? I cannot find the taste in the migrations, especially the seed method and adding data with new version. Also once you find yourself writing SQL into the methods, I think it is game over. I somehow find it dangerous and feel more safe in SQL scripts, mostly when deploying to production.
Santhos
It sounds nice, but also a bit inconsistent. My problem is mostly the data part. How do you deal with adding data? Let's say you are adding a new table and it is a enumeration like table and you have 200 labels to add. Do you place it in the seed method? And what if the data changes until next deploy. Do you then remove it from seed method? Or do you use up and down to do the job?
Wiktor Zychla
@Santhos: I never add actual data in the Seed but rather, in the migration (Up), using manual sql. That's the only way, as the metadata could possibly change in future. There is nothing wrong, I would write handmade sql when migrating the db anyway, using any other approach than EF.
|