如何在实体框架 6(代码优先)中调用存储过程? [英] How to call Stored Procedure in Entity Framework 6 (Code-First)?
本文介绍了如何在实体框架 6(代码优先)中调用存储过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 Entity Framework 6 非常陌生,我想在我的项目中实现存储过程.我有一个存储过程如下:
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
部门
类:
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?
推荐答案
您可以在 DbContext
类中调用存储过程,如下所示.
You can call a stored procedure in your DbContext
class as follows.
this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);
但是如果您的存储过程返回多个结果集作为您的示例代码,那么您可以在 MSDN 上看到这篇有用的文章
But if your stored procedure returns multiple result sets as your sample code, then you can see this helpful article on MSDN
这篇关于如何在实体框架 6(代码优先)中调用存储过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文