In this article we are going to learn step by step how to execute stored procedure which you have already created in SQL Server in code first approach in entity framework.

STEP 1

Execute following query in SQL Server

  1. CREATE DATABASE ENTITYDB
  2. GO
  3. USE ENTITYDB
  4. GO
  5. CREATE TABLE tblDepartments
  6. (
  7. DepartmentID INT PRIMARY KEY IDENTITY(1,1),
  8. DepartmentName VARCHAR(20)
  9. )
  10. INSERT INTO tblDepartments VALUES
  11. ('IT'),('HR'),('ACCOUNT')
  12. GO
  13. CREATE TABLE tblEmployees
  14. (
  15. EmployeeID INT PRIMARY KEY IDENTITY(1,1),
  16. Name VARCHAR(50),
  17. Age INT,
  18. Gender VARCHAR(10),
  19. DepartmentID INT
  20. )
  21. GO
  22. INSERT INTO tblEmployees VALUES
  23. ('MARK',21,'MALE',1),
  24. ('JOHN',22,'MALE',1),
  25. ('MACK',23,'MALE',2),
  26. ('RIYA',20,'FEMALE',2),
  27. ('ABRAM',21,'MALE',3)
  28. GO
CREATE PROCEDURE FOR GET ALL EMPLOYEE WITH DEPARTMENT
  1. CREATE PROCEDURE SP_GETEMPLOYEE
  2. AS
  3. BEGIN
  4. SELECT E.EMPLOYEEID,E.NAME,E.GENDER,E.AGE,D.DEPARTMENTNAME FROM TBLEMPLOYEES E JOIN TBLDEPARTMENTS D
  5. ON E.DEPARTMENTID=D.DEPARTMENTID
  6. END
CREATE PROCEDURE FOR GET EMPLOYEE BY EMPLOYEEID
  1. CREATE PROCEDURE SP_GETEMPLOYEEBYEMPLOYEEID 2
  2. (
  3. @EMPID INT
  4. )
  5. AS
  6. BEGIN
  7. SELECT E.NAME,E.AGE,E.GENDER,D.DEPARTMENTNAME FROM TBLEMPLOYEES E JOIN TBLDEPARTMENTS D
  8. ON E.DEPARTMENTID=D.DEPARTMENTID
  9. WHERE E.EMPLOYEEID=@EMPID
  10. END
STEP 2

Open visual studio and add new empty website, then add reference of System.Data.Entity

For adding this, here's the image.

Right click in references folder and open Nuget and download Entityframework dll and install it. After installation it gets automatically added in your references folder.



STEP 3

Now add the following two classes:
  1. EmployeeContext.cs
  2. Employee.cs

EmployeeContext.cs

  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Data.Entity;
  4. using System.Data.SqlClient;
  5. namespace SqlProcAccessInCodeFirstApproach
  6. {
  7. public class EmployeeContext : DbContext
  8. {
  9. public EmployeeContext()
  10. : base("DBCS")// DBCS name of connection string it available in Web.Config
  11.   {
  12. }
  13. public List<Employee> GetAllEmployee()
  14. {
  15. List<Employee> Employees = new List<Employee>();
  16. Employee emp;
  17. using (EmployeeContext cx = new EmployeeContext())
  18. {
  19. var result = cx.Database.SqlQuery<Employee>("SP_GETEMPLOYEE", "");//Here you also write sql query.
  20. foreach (Employee e in result)
  21. {
  22. emp = new Employee();
  23. emp.EmployeeID = e.EmployeeID;
  24. emp.Name = e.Name;
  25. emp.Gender = e.Gender;
  26. emp.Age = e.Age;
  27. emp.DepartmentName = e.DepartmentName;
  28. Employees.Add(emp);
  29. }
  30. }
  31. return Employees;
  32. }
  33. public Employee GetEmployeeByID(int ID)
  34. {
  35. EmployeeContext cx = new EmployeeContext();
  36. SqlParameter param = new SqlParameter("@EMPID", ID);
  37. var result = cx.Database.SqlQuery<Employee>("SP_GETEMPLOYEEBYEMPLOYEEID @EMPID", param).SingleOrDefault();//Here you also write sql query.
  38. return result;
  39. }
  40. }
  41. }
Employee.cs
  1. namespace SqlProcAccessInCodeFirstApproach
  2. {
  3. public class Employee
  4. {
  5. public int EmployeeID { get; set; }
  6. public string Name { get; set; }
  7. public string Gender { get; set; }
  8. public int Age { get; set; }
  9. public string DepartmentName { get; set; }
  10. }
  11. }
Note

Add connection string in web.config file
  1. <connectionStrings>
  2. <add name="DBCS" connectionString="SERVER=piyush-pc;DATABASE=ENTITYDB;USER ID=sa;PASSWORD=pass.123" providerName="System.Data.SqlClient"/>
  3. </connectionStrings>
You have to write provider name in connection string.

STEP 4

Add a new web page and give it a name.

Now write the following code within form tag in your aspx page:

WebForm1.aspx
  1. <div>
  2. <asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True" CellPadding="4"
  3. ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
  4. <AlternatingRowStyle BackColor="White" />
  5. <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
  6. <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
  7. <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
  8. <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
  9. <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
  10. <SortedAscendingCellStyle BackColor="#FDF5AC" />
  11. <SortedAscendingHeaderStyle BackColor="#4D0000" />
  12. <SortedDescendingCellStyle BackColor="#FCF6C0" />
  13. <SortedDescendingHeaderStyle BackColor="#820000" />
  14. </asp:GridView>
  15. <br />
  16. <table border="1" id="tblShow" runat="server" visible="false">
  17. <tr>
  18. <td colspan="2">
  19. <b>
  20. <asp:Label ID="lblName" Text="" runat="server" /></b>
  21. </td>
  22. </tr>
  23. <tr>
  24. <td>
  25. Gender
  26. </td>
  27. <td>
  28. <asp:Label ID="lblGender" Text="" runat="server" />
  29. </td>
  30. </tr>
  31. <tr>
  32. <td>
  33. Age
  34. </td>
  35. <td>
  36. <asp:Label ID="lblAge" Text="" runat="server" />
  37. </td>
  38. </tr>
  39. <tr>
  40. <td>
  41. Department Name
  42. </td>
  43. <td>
  44. <asp:Label ID="lblDName" Text="" runat="server" />
  45. </td>
  46. </tr>
  47. </table>
  48. </div>
And write the following code in your webform cs page.

WebForm1.aspx.cs
  1. using System;
  2. namespace SqlProcAccessInCodeFirstApproach
  3. {
  4. public partial class WebForm1 : System.Web.UI.Page
  5. {
  6. EmployeeContext cx;
  7. protected void Page_Load(object sender, EventArgs e)
  8. {
  9. if (!IsPostBack)
  10. {
  11. BindGrid();
  12. }
  13. }
  14. void BindGrid()
  15. {
  16. using (cx = new EmployeeContext())
  17. {
  18. GridView1.DataSource = cx.GetAllEmployee();
  19. GridView1.DataBind();
  20. }
  21. }
  22. protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  23. {
  24. int i = GridView1.SelectedIndex;
  25. int empId = Convert.ToInt32(GridView1.Rows[i].Cells[1].Text);
  26. using (cx = new EmployeeContext())
  27. {
  28. Employee emp = cx.GetEmployeeByID(empId);
  29. lblName.Text = emp.Name;
  30. lblGender.Text = emp.Gender;
  31. lblAge.Text = emp.Age.ToString();
  32. lblDName.Text = emp.DepartmentName;
  33. tblShow.Visible = true;
  34. }
  35. }
  36. }
  37. }
For knowing more about code first approach in entity framework refer my previous article on code first approach.