I am very new to Entity Framework 6 and I want to implement stored procedures in my project. I have a stored procedure as follows:
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:
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 can I call the stored procedure and pass parameters into it?
When EDMX create this time if you select stored procedured in table select option then just call store procedured using procedured name...
This is what EF (DB first) generates in the DbContext class:
You can call a stored procedure in your
DbContext
class as follows.But if your stored procedure returns multiple result sets as your sample code, then you can see this helpful article on MSDN
Stored Procedures with Multiple Result Sets
All you have to do is create an object that has the same property names as the results returned by the stored procedure. For the following stored procedure:
create a class that looks like:
and then call the procedure by doing the following:
The result will contain a list of
ResultForCampaign
objects. You can callSqlQuery
using as many parameters as needed.I solved it with
ExecuteSqlCommand
Put your own method like mine in DbContext as your own instances:
so you can have a method in your code-behind like this :
this is my SP :
hope helped you
You can now also use a convention I created which enables invoking stored procedures (including stored procedures returning multiple resultsets), TVFs and scalar UDFs natively from EF.
Read more
Read more.