简体   繁体   中英

ExecuteStoreCommand returns -1 , EntityFramework , C#?

I wanna get the next automatically incrementing primary key, Here I understood to use T-SQL for doing that. So I wrote the following method :

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

but it returns -1, whereas it must be 4 right now.

PS: When I execute below T-SQL in SQL Management Studio , it returns 4

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

You need to use 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);
}

The SQL query will return a decimal so you need to convert it to int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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