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?
It work for me at code first. It return a list with matching property of view model(StudentChapterCompletionViewModel)
Updated for Context
Context is the instance of the class that Inherit DbContext like below.
if you wanna pass table params into stored procedure, you must necessary set TypeName property for your table params.
You are using
MapToStoredProcedures()
which indicates that you are mapping your entities to stored procedures, when doing this you need to let go of the fact that there is a stored procedure and use thecontext
as normal. Something like this (written into the browser so not tested)If all you really trying to do is call a stored procedure directly then use
SqlQuery