Overview
In this article, we will see how to work with Data Access using Entity Framework in MVC. Kindly refer to my previous articles, so that you could get connected to this article. Refer to:
Introduction
As we saw in our previous articles, Controller responds to URL, gets data from Model and hands it over to View . Then, View actually presents the data.
NOTE: The models, here, can be Entities or Business Objects .
In an earlier part of our article Understanding Viewdata and Viewbag in MVC, we used a class called employee.cs where we used various get and set methods to access that data,
Similarly, we used Controllers to display those data; they are:
But actually, we had harcoded our Values. Here, I want to pass the data from SQL Server. So, here, we are having a table called Employee that stores employee information. I want to pass this data.
We will be using Entity Framework here. To install the Entity Framework in your project, just right click on your Project->Manage Nugget Package.
And, search for the Entity Framework.
Click on Accept and Install. It will be successfully installed.
Once you have installed it, go to References folder and check whether Entity Framework has been added or not.
Now, let's add a class file, EmployeeContext.cs, in Models folder.
Now, just add these lines of code in that class:
Look at the code. Now, the Employee Context is getting inherited from DbContext and Employee is class file in which we are accessing the values .
Now, we are getting a compilation error on DbContext. When we click it, it says:
Here, the namespace is required to be added. Using System.Data.Entity add that namespace.
The purpose of this class is to establish a connection to our database. We need a connection string to establish connection. So, add the following connection string in your web.config file.
- <connectionStrings>
- <add name="EmployeeContext" connectionString="server=IBALL-PC;database=HotelManagement ; integrated security=SSPI" providerName="System.Data.SqlClient"/>
- </connectionStrings>
We have written the name EmployeeContext which is the file we created as Employee Context. Now, switch to Employee.cs file and just write this code:
We need to add the Table (“EmployeeDetails”), for we are fetching data from our database .
Similarly, add these two namespaces:
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
Now, let's switch back to our controller and write these lines. As we will be passing, so in our action method, we specify the id parameter .
We will be creating a new object. Here is the linked list where we specify our EmpId and access those:
Now, just run the solution and pass controllername/Action/id
You will get an output:
We fetched results from our database by specifying respective ids.
Conclusion: This was about Data access in MVC using Entity Framework . I hope this article was helpful.