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

时间:2015-05-08 09:13:38

标签: asp.net vb.net entity-framework stored-procedures

我希望下面的存储过程向表中插入一条新记录,并在执行时返回相同的记录。我试图利用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)

1 个答案:

答案 0 :(得分:1)

从异常中可以清楚地看出,您正在将Stored_Procedure_Test.insertQuery_Result的对象转换为对象类型Material。您的SP返回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