【问题标题】:ExecuteStoreCommand returns -1 , EntityFramework , C#?ExecuteStoreCommand 返回 -1 , EntityFramework , C#?
【发布时间】:2011-10-13 07:10:40
【问题描述】:

我想获得下一个自动递增的主键,Here 我知道使用 T-SQL 来做到这一点。 所以我写了以下方法:

public int GetLastNewsID()
{
    const string command = @"SELECT IDENT_CURRENT ('{0}') AS Current_Identity;";
    int id = EntityModel.ExecuteStoreCommand(command, "News");
    return id;
}

但它返回 -1,而它现在必须是 4。

附注: 当我在 SQL Management Studio 中执行以下 T-SQL 时,它返回 4

USE T;
GO
SELECT IDENT_CURRENT ('NEWS') AS Current_Identity;
GO

【问题讨论】:

    标签: c# sql tsql entity-framework identity-column


    【解决方案1】:

    你需要使用ExecuteStoreQuery

    public int GetLastNewsID()
    {
        const string command = @"SELECT IDENT_CURRENT ({0}) AS Current_Identity;";
        var id = EntityModel.ExecuteStoreQuery<decimal>(command, "News").First();
    
        return Convert.ToInt32(id);
    }
    

    SQL 查询将返回decimal,因此您需要将其转换为int

    【讨论】:

    • 我已经完成了,但我收到了一个异常:InvalidOperationException.The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
    【解决方案2】:

    【讨论】:

    • 是的,ExecuteStoreCommand() 返回受影响的行数,只要您有(默认)set nocount off。使用 set nocount on 它返回 -1。
    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多