gpt4 book ai didi

c# - 如何在 Entity Framework 6(代码优先)中调用存储过程?

转载 作者:IT王子 更新时间:2023-10-29 03:28:51 25 4
gpt4 key购买 nike

我是 Entity Framework 6 的新手,我想在我的项目中实现存储过程。我有一个存储过程如下:

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
}

我的问题是:如何调用存储过程并将参数传递给它?

最佳答案

您可以调用 DbContext 类中的存储过程,如下所示。

this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);

但是如果你的存储过程返回多个结果集作为你的示例代码,那么你可以在 MSDN 上看到这篇有用的文章

Stored Procedures with Multiple Result Sets

关于c# - 如何在 Entity Framework 6(代码优先)中调用存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20901419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com