In this section we will discuss code-first workflow in detail. Some developers think that code-first workflow is only good for a Greenfield project and not when you have an existing database. In this section, we will explore that how can we use code-first workflow successfully with an existing database or a new database.
We have already discussed code-First workflow in the article three approaches of EF , if you have directly landed here then I will highly recommend you to read that article first so that you will have some idea about Entity Framework in general and about its different approaches .
Also read the article which approach is really better, to know the pros and cons of code-first approach and then decide whether you want to proceed with the code-First approach or database-First approach.
This section covers following topics :
• code-first workflow with a new database.
• code-first with an existing database.
• Migrations in detail.
• Different ways to seed the database with test data or reference data.
• Overriding Code-First convention with data-annotation.
•Overriding Code-First convention with fluent API.
• Establishing relationships between tables correctly using Fluent API.
Being a c# developer, I always prefer to use a code-first approach, it gives a developer full control over the database, we can do everything on the database with just two commands like add-migration and update-database, right from our application. Not only this, but we can also create a stored procedure, triggers, views, and we can seed a database table with a reference or dummy data right from our application without touching the database and it is awesome, we don't need to go to SSMS and fires SQL query to design database, we just focus on our code and Entity Framework takes care of all.
Untill you don't have a complete existing database always prefer to use a code-first approach, even with an existing database you can follow the code-first approach with some reverse engineering which we will discuss in a later article.