Learn How to Use Entity Framework in MVC

0
1464
Entity Framework

Entity Framework

Entity Framework is an ORM framework that works with relational database. It deals with data as objects and properties. ORM is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way, without much programming .With the use of Entity Framework, we write query using LINQ, and retrieve and manipulate data. The Entity Framework provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

Advantage of Entity Framework

1) High Productivity – It makes the developer’s life easier as it is easy to implement and saves time in writing query in c# instead of Database.
2) Easy to maintain – Easy to maintain as fewer lines of code is used to fetch data from Database.

Advantage of Entity Framework

So let’s start with an example how to use entity framework. In the below example, we are using database first approach.

First of all create a simple database in sql server and create tables. I have created DemoDB and Roles and Users table.

1

Open visual studio then click on file new project select asp.net MVC web application select Internet Application.

2

Now to use entity framework, we have to install entity framework in project, to install open NuGet package manager and install Entity framework.

3

Now, create a new folder in project and rename it to EDMX. Right click on the folder and click on add new item. A pop up will appear on right side. On the pop up click on Data and then select ADO.NET Entity Data Model rename it to DemoDB.edmx and click on Add button.

An edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An edmx file also contains information that is used by the ADO.NET Entity Data Model Designer to render a model graphically.

4

A popup will appear after clicking on add button. Select generate from database and click on next.

5

Now select your database server and database and select database objects and click on finish button.

6

7

Learn HTML5 Programming For Beginners

Inside the EDMX folder, you can see DemoDB.edmx file is created. When you expand it you can see the DemoDB.tt file is created again. When you expand DemoDB.tt file, you can see the entire data base objects as a class are created. You can open them and see the properties, etc. inside their classes.

8

You are almost done . Now open your home controller and paste the code below inside Index Actionresult. You can create model and put user list in model and use that model in view.

9

Now open index.cshtml view inside ViewHome folder and paste the below code in it

10

Now run the programme and see the results.

11

LEAVE A REPLY

Please enter your comment!
Please enter your name here