Wednesday 20 May 2015

Data Access from databse using Entity framework


Here we will learn How to access value from database using entity framework in Asp.net MVC.
1.   Go to your SQL server Management system and create a database and execute the following script.
Create Table Student
(
     StudentID int identity primary key,
     StudentName nvarchar(50),
     Gender nvarchar(50),
     SchoolName nvarchar(50)
)
GO



Insert into Student values ('Munesh','Male','VIT')
Insert into Student values ('Rahul','Male','ABC')
Insert into Student values ('Reet','Female','XYZ')
Insert into Student values ('Anshuman','Male','PQR')

2.   How a controller respond to a user request  :- It Gets the data from modal a modal and transfer this request to  the view then view render the data. Modal can be a entity or a business objects.
3.   Retrieving the data from database table using entity framework ,1st we have to install entity framework using nugget package manager for this go to Entity framework tutorial. Add a reference of entityFramework.
4.   Now add  a StudentContext.cs class to your modal folder
using System.Data.Entity;

public class StudentContext : DbContext
{
    
public DbSet<Student>  _students {get; set;}
}

The use of StudentContext class is for establishing the connection to our database
5.   Now add a connection string  in Web.Config file
<connectionStrings>
  
<add name="StudentContext" 
        
connectionString="server=.; database=MVCApplication; integrated security=SSPI"
        
providerName="System.Data.SqlClient"/>
</connectionStrings>


6.   Create a class As Student.cs in Modal folder and MAP it with database table, for mapping this employee modal class with database table we will use “Table” attribute. For this Attribute we need DataAnnotations namespace.


using System.ComponentModel.DataAnnotations.Schema;


namespace MvcApplication1.Models
{
   [Table("Student")]
    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public string StudentSchool { get; set; }
    }
}


7.   Now we need to change in Controller class for getting the value from database. For this  I added a Controller class with name Home Controller by default it contain a Index method.
1.   First in index method we need to call the “StudentContex”t class for making the connection this StudentContext class it connected with Web config file.
2.   Here if we want data according to ID then we need to pass ID to this  function and then we will retrieve student detail according to that id.
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
       
        public ActionResult StudentDetail(int id)
        {
            StudentContext _context = new StudentContext();
           Student _student =  _context._studentDb.Single(c => c.StudentId         == id);

            return View(_student);
        }

    }
}


8.   Now we will add a view for this method so for that see the following code
@model MvcApplication1.Models.Student

@{
    ViewBag.Title = "StudentDetail";
}

<h2>StudentDetail</h2>

<table style="font-family:Arial">
    <tr>
        <td>
            Student ID:
        </td>
        <td>
            @Model.StudentId
        </td>
    </tr>
    <tr>
        <td>
            Name:
        </td>
        <td>
            @Model.StudentName
        </td>
    </tr>
    <tr>
        <td>
            Gender:
        </td>
        <td>
            @Model.Gender
        </td>
    </tr>
    <tr>
        <td>
            City:
        </td>
        <td>
            @Model.SchoolName
        </td>
    </tr>
</table>


9.   Here we need to remember that in  “Global.asax” file we will add a line of code
Database.SetInitializer<MvcApplication1.Models.StudentContext>(null);



Here “Database” is stored in “using System.Data.Entity” namespace. The use of this “SetInitializer” is that , It creates table if we don’t have table in database which is given in Employee modal class by us as an Table Attribute.

10.                Run Your application and give the path as “http://localhost/MvcApplication1/student/StudentDetail/1”  or you can set Controller name and Action method name in Route.Confing File you will get expected result from here means it show the data which is exists in database table on ID =1.






Note :-  While Running if you get error like “Login failed for user 'IIS APPPOOL\DefaultAppPool'” then you refer this link

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...