Database First Approach in Entity Framework

Entity Framework Database First approach is also known as Schema First Approach; this is the most popular or easy approach that new developer start with entity framework development, in this approach object gets generated from database directly.

As a developer, if you are already familiar with SQL Database development, then this approach can help you in rapid application development.

Step 1: right click on your .net project and add an "Ado.Net Entity Data Model" file as shown below. the file extension would be .edmx

entity framework tutorial

EF Database First Approach Example

Step 2:
Now you can either create an empty model or create a model from database, (in this example we create a model from existing database), so select "Generate from Database".

entity framework tutorial

Setup Database Connection Details

Step 3:
To connect database, you can create existing connection from list or create a new connection, here we create a new connection, so you can learn how to create a new connection, look at the picture below, and please use “SQL server authentication”, so the same user name and password can be used in connection string configuration.

entity framework database connection

Select Database Objects

Step 4:
After connecting to database, Fetch all database objects you want to use in this application, also instead of fetching all you can chose objects you want in application by checking check boxes.

database objects in entity framework

Stp 5:
Now your edmx file is loaded with database object information, so compile the project before you start writing code for database update and make sure you have set the connection string details properly.

edmx objects in entity framework
DBContext Class Ready

Step 6:
Now our entity framework is ready to perform any database operation, so let’s create an instance of DbContext class and start working with database.

Here is an example how you can create an instance of DbContext

public tbStudent getStudent(int id) {
tbStudent _student = null;
using (Entities context = new Entities())
{
_student = context.tbStudents
.Where(s => s.studentId == id)
        .FirstOrDefault<tbStudent>();
    }
    return _student;
}

dbContext objects in entity framework

While creating new instance of context object, always do with using keyword, then we don’t have to dispose the object after use, once it comes out of the scope, it will be disposed automatically

 
Database First in Entity Framework
Learn entity framework orm using c#, entity framework core and earlier version of entity framework, all tutorials are written in c#.
Entity Framework Interview Questions

SQL interview questions
Entity Framework C# Examples | Join .Net C# Course