ExecuteStoreCommand returns -1 , EntityFramework , C#?

本文关键字:EntityFramework ExecuteStoreCommand returns | 更新日期: 2023-09-27 18:11:12

我想获得下一个自动递增的主键,在这里我理解使用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

p。史:当我在SQL Management Studio中执行下面的T-SQL时,它返回4

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

ExecuteStoreCommand returns -1 , EntityFramework , C#?

您需要使用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

阅读有关返回值的部分内容:

http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.executestorecommand.aspx