【问题标题】:Utilize returned value from Stored Procedure using Entity Framework in VB.Net在 VB.Net 中使用实体框架利用存储过程的返回值
【发布时间】:2015-05-08 09:13:38
【问题描述】:

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      相关资源
      最近更新 更多