ExecuteStoreCommand返回-1,EntityFramework,C#?

Moh*_*yan 1 c# sql t-sql entity-framework identity-column

我想得到下一个自动递增的主键,在这里我理解使用T-SQL来做到这一点.所以我写了以下方法:

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

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

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

USE T;
GO
SELECT IDENT_CURRENT ('NEWS') AS Current_Identity;
GO
Run Code Online (Sandbox Code Playgroud)

Era*_*nga 6

您需要使用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);
}
Run Code Online (Sandbox Code Playgroud)

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