Javatpoint Logo
Javatpoint Logo

ASP.NET MVC Entity Framework

It is a data access framework which used to create and test data in the visual studio. It is part of .NET Framework and Visual Studio. The latest package is shipped as Entity Framework NuGet Package. The latest version is Entity Framework 6.0.

We are using it in our ASP.NET MVC application. First, we will create a project then adding models to it.

This example required the following tools and technologies:

  • Visual Studio 2017
  • .NET 4.5
  • Entity Framework 6.0
  1. Create a MVC Project
  2. Select file menu from menu bar and select new project.

    ASP Framework 1

    Provide name to the project and hit ok.

    ASP Framework 2

    Select template for the project and click ok.

    ASP Framework 3

    After clicking ok, visual studio creates a project that has following structure. In our case project structure looks like this:

    ASP Framework 4

    Now, create a model for table in the database. Right click on the Models folder and add new class by setting name as Student.cs. Modify this class with the following code.


    Model

    // Student.cs

    Create a database context class that is used to coordinate with Entity Framework for a given data model. Place this class in Models folder. Right click on the Models folder and add a class. Provide a name RecordContext.cs to the class. Modify your class with the following code.

    // RecordContext.cs


Create migration

To create migration, open Package Manager Console by going through view->other windows->Package Manager Console . In Package Manager Console run the following command.

We are executing this command in the following screenshot.

ASP Framework 5

After executing this command, framework creates a Migration folder in the project and a Configuration.cs file.

We are updating this file with the following code.

// Configuration.cs

Save this file and run both the following commands in Package Manager Console.

After it, run this also

ASP Framework 6

This command will create initials for the project inside migration folder.

Create scaffolding to display data on the web page.

ASP Framework 7

Select and add scaffold.

ASP Framework 8

Add controller and provide details to create view as well.

ASP Framework 9

Controller

A new StudentsController has added that contains some auto generated code as given below.

// StudentsController.cs

A Student folder created inside the View folder. This folder contains some auto generated files like Index, Create, Delete etc. The index file contains the following code.

// Index.cshtml

Press Ctrl+F5 to run this file then this will produce the following output.

ASP Framework 10




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA