Free Web Development Online Tutorials, Learn to Code
Learn Entity Framework with C#, Entity Framework Core, Code First, DB First Approach

What is Database First Approach in Entity Framework

How EF Database First Approach Works

Database First approach is also known as Schema First Approach; this is the most popular or easy approaches that new developer start with entity framework development.

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

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

Comment
Name
Email
Website
Subscribe
 
Database First in Entity Framework