简体   繁体   English

在VB.Net中使用实体框架利用存储过程的返回值

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

I hope the below stored procedure inserts a new record to the table and returns the same when executed. 我希望下面的存储过程在表中插入一条新记录,并在执行时返回相同的记录。 I tried to utilize this stored procedure from Entity Framework as shown far below. 我试图利用实体框架中的该存储过程,如下所示。 The new record is properly inserted. 新记录已正确插入。 But I don't know why I couldn't get the value returned from the procedure. 但是我不知道为什么我无法从过程中返回值。

Stored Procedure: 存储过程:

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 Code: 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

When I try this code, I get the following error 当我尝试此代码时,出现以下错误

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

at the line Dim mat As Material = CType(element, Material) 在线Dim mat As Material = CType(element, Material)

It is very clear from exception that you are casting and object of Stored_Procedure_Test.insertQuery_Result to object type of Material . 从异常非常清楚,您正在将Stored_Procedure_Test.insertQuery_Result的对象Stored_Procedure_Test.insertQuery_Result转换为Material对象类型。 Your SP returns collection of objects which are of type Stored_Procedure_Test.insertQuery_Result . 您的SP返回类型为Stored_Procedure_Test.insertQuery_Result的对象的Stored_Procedure_Test.insertQuery_Result So what you can do is get value from the object returned by SP like this. 因此,您可以做的就是从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;

So your complete code should look like this 因此,您的完整代码应如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM