Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
I am very new to Entity Framework 6 and i want to implement Stored Procedure in my project. I searched in google deeply but couldn't find any solution in which i can follow the implementation. I have a stored procedure like below.


SQL
ALTER PROCEDURE [dbo].[insert_department]
@Name [varchar](100)
AS
BEGIN
INSERT [dbo].[Departments]([Name])
VALUES (@Name)

DECLARE @DeptId int
SELECT @DeptId = [DeptId]
FROM [dbo].[Departments]
WHERE @@ROWCOUNT > 0 AND [DeptId] = scope_identity()

SELECT t0.[DeptId]
FROM [dbo].[Departments] AS t0
WHERE @@ROWCOUNT > 0 AND t0.[DeptId] = @DeptId
END


Department Class

C#
public class Department
{

    public int DepartmentId { get; set; }       
    public string Name { get; set; }

}

modelBuilder 
.Entity<Department>() 
.MapToStoredProcedures(s => 
s.Update(u => u.HasName("modify_department") 
               .Parameter(b => b.Department, "department_id") 
               .Parameter(b => b.Name, "department_name")) 
 .Delete(d => d.HasName("delete_department") 
               .Parameter(b => b.DepartmentId, "department_id")) 
 .Insert(i => i.HasName("insert_department") 
               .Parameter(b => b.Name, "department_name")));

protected void btnSave_Click(object sender, EventArgs e)
  {
          string department = txtDepartment.text.trim();

         // Here i want to call the stored procedure to insert values

  }


My problem is how do i call the stored procedure and pass parameters into it. Please help me out. Thanks in advance.
Posted

Check this sample application:

Entity Framework for Beginners[^]
 
Share this answer
 
v2
check this link might be helpful for you:

how to execute stored procedures in sqlquery in the dbcontext
 
Share this answer
 
v2
actually Entity Framework does not support SP
but if you insist to use it , i answered this question in link below

How to call Stored Procedure in Entity Framework 6 (Code-First)?
 
Share this answer
 
 
Share this answer
 
Comments
apurba001 3-Jan-14 10:05am    
Thanks Jameel for your reply. I followed the link you have posted but it does not given the way how to execute the stored procedure from code behind.
Refer - Code First Insert/Update/Delete Stored Procedures[^].

It describes how to configure your Code First model to use stored procedures and pass parameters to them.
 
Share this answer
 
Comments
Member 4750507 7-Mar-14 18:46pm    
That article is only for insert/update/delete stored procedures. What about just general stored procedures that do a bunch of things and return a recordset? That aren't related to insert/update/delete?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900