在 VB.Net 中使用 Entity Framework 利用存储过程的返回值

Utilize returned value from Stored Procedure using Entity Framework in VB.Net

我希望下面的存储过程在执行时向 table 和 returns 插入一条新记录。我尝试使用 Entity Framework 中的这个存储过程,如下所示。新记录已正确插入。但是我不知道为什么我无法从过程中获取返回值。

存储过程:

USE [Materials]
GO

CREATE PROCEDURE [dbo].[insertQuery1]
@Code NVARCHAR(50),
@Name NVARCHAR(100)
AS
BEGIN
INSERT INTO dbo.Materials
(Code, Name)

Values (@Code, @Name)

Select mat.ID, mat.Code, mat.Name from dbo.Materials mat where mat.ID = SCOPE_IDENTITY()

END

ASPX.VB代码:

Protected Sub testing_Click(sender As Object, e As EventArgs)
    Dim code As String
    Dim name As String
    Dim element As Object
    code = "New Code"
    name = "New Element"
    element = ent.insertQuery(code, name)
    Dim mat As Material = CType(element, Material)
End Sub

当我尝试此代码时,出现以下错误

Unable to cast object of type 'System.Data.Objects.ObjectResult`1[Stored_Procedure_Test.insertQuery_Result]' to type 'Stored_Procedure_Test.Material'.

在第 Dim mat As Material = CType(element, Material)

很明显,您正在将 Stored_Procedure_Test.insertQuery_Result 的对象类型转换为 Material 的对象类型。您的 SP returns 类型 Stored_Procedure_Test.insertQuery_Result 对象集合。所以你可以做的就是像这样从 SP 返回的对象中获取值。

Stored_Procedure_Test.insertQuery_Result element = ent.insertQuery(code, name).FirstOrDefault();
//And you can access properties of this object like this
string name=element.Name;

所以你的完整代码应该是这样的

Protected Sub testing_Click(sender As Object, e As EventArgs)
Dim code As String
Dim name As String
code = "New Code"
name = "New Element"
Dim element As Stored_Procedure_Test.insertQuery_Result = ent.insertQuery(code, name).FirstOrDefault();

//Now you can directly use the `element` to access values returned from SP.
End Sub