[ASP.NET MVC] Code first vs Database First

When you start with ASP.NET, everyone asks this question. It’s like asking whether you should make the egg first and let it hatch into a chicken, or make the chicken first and let it lay the egg?

Whichever you pick, there are differences you need to know so you can choose right — and then commit to it

original

1. Explanation

Code First Database First
Write the Model classes in C# code
Generate the Database from the Model classes
Generate the Model from the Database
The Model classes cannot be edited

2. Pros and cons

Code first Database first
Pros Very popular (because developers usually don’t like designing DBs, but do like designing classes)

Full control over the model code; adding, removing and changing properties is extremely easy
No need to rack your brain over the DB. With this approach the DB is just a “lump” of data you pull out and use
You can version control the Database
Less popular

The DB can be developed separately
You can use an existing DB
Entity Framework creates the Entity classes for you
Cons Structural changes made directly on the DB get lost

Hard to control which columns are created in the Db
A bit awkward when combined with an existing Db
You can’t change the Generated code (it gets lost on the next DB structure change)

Hard to add DataAttributes and DisplayAttributes to the model classes
You have to rack your brain to express parent-child relationships between classes
Every time the DB structure changes you have to update the EDMX and regenerate the Model classes to reflect that change

You have to rack your brain to express parent-child relationships between classes. Every time the DB structure changes you have to update the EDMX and regenerate the Model classes to reflect that change

3. What future for ASP.NET Core?

At the time of writing, ASP.NET Core will still support Database First long term, but it has some very annoying bugs that make creating Entity Classes from an existing Database a bit difficult

A tentative conclusion: Code first is the future, but if you like, you can still use Database First

That’s all :D