简体   繁体   English

EF 4.1 代码优先:执行存储过程并返回 IDENT

[英]EF 4.1 Code First: Execute Stored Proc and return IDENT

I'm attempting to use context.Database to execute a stored proc that inserts a record and returns the identity.我正在尝试使用context.Database来执行插入记录并返回标识的存储过程。 I know my proc works, using either an output parameter, select, or return, but I cannot get either ExecuteSqlCommand or SqlQuery<int> to return the identity.我知道我的 proc 可以工作,使用 output 参数、select 或返回,但我无法让ExecuteSqlCommandSqlQuery<int>返回身份。

Using a stored proc with return,使用带返回的存储过程,

INSERT INTO TableA (FieldA, FieldB)
RETURN SCOPE_IDENTITY

I see a return value of 1010966 from SSMS我看到 SSMS 的返回值为1010966

DECLARE @return_value int
EXEC    @return_value = spInsertRecord
SELECT  'Return Value' = @return_value

But nothing I have done in my application returns a valid value.但是我在我的应用程序中所做的任何事情都没有返回有效值。

Int64 result = context.Database.ExecuteSqlCommand

always returns 3 and I get a casting error referencing Decimal when using SqlQuery<int> .总是返回 3,并且在使用SqlQuery<int>时出现引用 Decimal 的转换错误。 I made an attempt with an output parameter, but wasn't able to get the code to execute properly, so have focused on the app consuming either SELECT SCOPE_IDENTITY or RETURN SCOPE_IDENTITY我尝试使用 output 参数,但无法使代码正确执行,因此专注于使用SELECT SCOPE_IDENTITYRETURN SCOPE_IDENTITY的应用程序

Short of creating models to replace the logic contained in the stored procedure, I'm open to any and all suggestions for returning the value for both the Stored Proc and application level.由于没有创建模型来替换存储过程中包含的逻辑,我对返回存储过程和应用程序级别的值的任何和所有建议持开放态度。

Here is how you can get this to work.以下是如何让它发挥作用。 In this example, my EntityManager is just a class that inherits from DBContext.在此示例中,我的 EntityManager 只是一个继承自 DBContext 的 class。

Test Table:测试表:

CREATE TABLE [dbo].[TableA](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [FieldA] [nvarchar](50) NULL,
    [FieldB] [nvarchar](50) NULL
) ON [PRIMARY]

Stored Proc:存储过程:

CREATE PROC spInsertRecord
    @FieldA NVARCHAR(50),
    @FieldB NVARCHAR(50)
AS

INSERT  TableA
    (FieldA, FieldB)
VALUES  
    (@FieldA, @FieldB)

SELECT  CAST(@@IDENTITY AS INT)

Calling Code (VB.NET)调用代码 (VB.NET)

Public Shared Function AddRecord(FieldA As String, FieldB As String) As Integer
    Try
        Using EM As New EntityManager
            Return EM.Database.SqlQuery(Of Integer)(
                "EXEC spInsertRecord @FieldA, @FieldB",
                New SqlParameter("FieldA", FieldA),
                New SqlParameter("FieldB", FieldB)).SingleOrDefault
        End Using
    Catch ex As Exception
        Throw New ApplicationException("An error occurred while executing AddRecord", ex)
    End Try
End Function

Consuming Code:消费代码:

Return AddRecord("Tom", "Halladay")

My result is the incrementing return value.我的结果是递增的返回值。 Hope this helps.希望这可以帮助。

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

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