Database First Approach In Entity Framework

Introduction

Entity Framework supports three different development approaches to use Entity Framework in your Application.

  1. Code First
  2. Model First
  3. Database first

Database First Approach

Database First Approach creates the Entity Framework from an existing database. It creates model codes from the database. The database in the project and those classes become the link between the database and controller.


The steps are mentioned below for using the Database First Approach.

Step 1

First Create Table in Database (SQL Server 2012)
  1. Create database and name it as Login.
  2. Add table (here Table name: tbllogin).
  3. Set primary key to Id column.


Step 2

Create new project in Visual Studio 2015
  1. Go to File-> New-> Project -> Web-> ASP.NET MVC4 Web Application-> Entry Application Name-> OK.
  2. Select a template-> Empty-> check MVC folder-> OK.

    Project is created with MVC folder.


Step 3

Now, you have to add Entity Framework into your Project.

  1. Go to Tools-> NuGet Package Manager-> Manage NuGet Packages for the solution.






  2. See in References, Entity framework is available.


Step 4

Select ADO.NET Entity Data Model
  1. Right click Models Folder-> Add-> Class-> Visual C#-> Data-> ADO.NET Entity data Model-> Entry Name-> ADD.





  2. Entity Data Model Wizard dialog.

    Select EF Designer from the database-> Next->New Connection




Enter your Server name-> Choose your authentication. I am using SQL Server authentication. Thus, we need to provide the user name and password-> Select your database-> Test Connection-> OK.



It includes the sensitive data in the connection string->next->Choose version of Entity Framework.



Include database objects to your model-> Finish.



Visual Studio will generate a database diagram for the table.



Now, you have an Entity Data Model file in your Model folder with all its necessary supportive files. The screen given below shows the auto generated entities file with DbContext inherited (Student.Context.cs). DbContext and DbSet are the ones that we need to establish a link between the model and the database. 

"tbllogin.cs" class is one where you will see all the properties.



Student.Context.cs



tbllogin.cs



I hope you liked it. Thanks.