2011-10-13 93 views
1

我想要下一个自动增加主键,Here我明白用T-SQL来做这件事。 所以我写了下面的方法:ExecuteStoreCommand返回-1,EntityFramework,C#?

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

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

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

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

回答

5

您需要使用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。关于返回值

+0

我已经做到了,但我recive一个例外:'In​​validOperationException.The转换为价值型“的Int32”失败,因为物化值为null。结果类型的泛型参数或查询必须使用可为空的类型。' –

+0

@Mohammad检查更新的答案 – Eranga

+0

没有区别,我再次收到异常! –