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
- CREATE DATABASE ENTITYDB
- GO
- USE ENTITYDB
- GO
- CREATE TABLE tblDepartments
- (
- DepartmentID INT PRIMARY KEY IDENTITY(1,1),
- DepartmentName VARCHAR(20)
- )
- INSERT INTO tblDepartments VALUES
- ('IT'),('HR'),('ACCOUNT')
- GO
-
- CREATE TABLE tblEmployees
- (
- EmployeeID INT PRIMARY KEY IDENTITY(1,1),
- Name VARCHAR(50),
- Age INT,
- Gender VARCHAR(10),
- DepartmentID INT
-
- )
- GO
- INSERT INTO tblEmployees VALUES
- ('MARK',21,'MALE',1),
- ('JOHN',22,'MALE',1),
- ('MACK',23,'MALE',2),
- ('RIYA',20,'FEMALE',2),
- ('ABRAM',21,'MALE',3)
- GO
CREATE PROCEDURE FOR GET ALL EMPLOYEE WITH DEPARTMENT- CREATE PROCEDURE SP_GETEMPLOYEE
- AS
- BEGIN
- SELECT E.EMPLOYEEID,E.NAME,E.GENDER,E.AGE,D.DEPARTMENTNAME FROM TBLEMPLOYEES E JOIN TBLDEPARTMENTS D
- ON E.DEPARTMENTID=D.DEPARTMENTID
- END
CREATE PROCEDURE FOR GET EMPLOYEE BY EMPLOYEEID- CREATE PROCEDURE SP_GETEMPLOYEEBYEMPLOYEEID 2
- (
- @EMPID INT
-
- )
- AS
- BEGIN
- SELECT E.NAME,E.AGE,E.GENDER,D.DEPARTMENTNAME FROM TBLEMPLOYEES E JOIN TBLDEPARTMENTS D
- ON E.DEPARTMENTID=D.DEPARTMENTID
- WHERE E.EMPLOYEEID=@EMPID
- 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:
- EmployeeContext.cs
- Employee.cs
EmployeeContext.cs