Hello guys! Entity Framework is one kind of ORM tool, which helps us to interact with database without any hassle. Here I assume that you are already familiar with the term "Entity Framework". There are approaches to interact with database, like database first and code first. However, the IT people already have an experience of working with database using database first approach, much before there was no ORM tool.
So today, I will be talking to you about Code First approach with entity framework.
A. What is code first approach? B. Why to choose code first? C. How to implement Code First Approach?
A. What is code first approach? The mapping between the store schema and the conceptual model represented by your code is handled by convention and by a special mapping API in code first approach. It is mainly useful in Domain Driven Design. Usually we are habituated to think about database design and creation when we start to develop application. We design and create database first then we start code to access that database to manipulate data.
As the name of the approach says, "code first", so in this approach we write code at first to generate database and we will run those codes to see database in DB server. You do not need to run the Entity Framework visual design tool, neither to design entities (Model First) nor to map entities to an existing database (Database First).
There is no XML file - no EDMX file - to represent your model and storage schemas. There is no need to generate entity classes from an EDMX.
B. Why to choose code first?
The following features can give you a clear picture that why should opt for it.
In Code first approach we do not need to think database, as the developer can start with domain classes.
Developer can focus on domain, which is required to fulfil business processes & requirements.
We can maintain database version on production server easily.
We can add or update business data in context initialization which are required in tables.
There is no need to generate any extension class.
Greater control on database using code.
We can also edit migration code to add additional changes to database like context initialization.
Code first approach will be more helpful if you are a hard code developer.
Code first approach helps us to get full control over our database design without much knowledge of SQL and DBA.
C. How to implement Code First Approach? As a developer, first you can start by writing C# or VB.net classes & context class. When you run your application, Entity Framework will create the new database (if not already exists) and map classes with your database using code-first conventions. We can configure our domain classes to override any default conventions to map with database tables using Data Annotation attributes & Fluent API.