这就是我的问题。我想用Linq to Sql中的自定义sql表达式来获取最后插入的Id。
我的insert方法:
public int Add(string Label)
{
_dbContext.ExecuteCommand("INSERT INTO Products (Label) VALUES (@Label);", Label);
_dbContext.SubmitChanges();
var lastId = _dbContext.ExecuteQuery<int>("SELECT Scope_Identity() as [Scope_Identity];").ToList()[0];
return lastId;
}
lastId总是返回null。当我在Sql Server中直接尝试这个查询(Insert + Select)时,它工作得很好,并返回最后插入的Id。我不想使用过程,也不能使用新的Product对象(我不可能使用InsertOnSubmit或其他任何东西)。
你能帮帮我吗?谢谢。
发布于 2009-08-05 06:30:31
好的,我已经知道怎么做了:
public int Add(string Label)
{
var query = String.Format("INSERT INTO Products (Label) VALUES (@Label); SELECT ProductId FROM Products WHERE ProductId = Scope_Identity();", Label);
var lastId = _dbContext.ExecuteQuery<int>(query).ToList()[0];
return lastId;
}
发布于 2009-08-03 07:26:27
尝试使用:
INSERT INTO Products (Label) OUTPUT inserted.ProductID VALUES (@Label);
抢夺
发布于 2012-03-27 23:56:27
我知道你已经回答了,但我发现还有另一种方法,它对我的特定场景很有用,需要编辑添加到表中的最新记录,而不需要知道这些记录的I:
public int Add(string Label)
{
var query = String.Format("INSERT INTO Products (Label) VALUES (@Label);", Label);
_dbContext.ExecuteCommand(query);
var lastId = _dbContext.ExecuteQuery<int>("SELECT IDENT_CURRENT('Products ')").First();
return lastId;
}
https://stackoverflow.com/questions/1220992
复制相似问题