如何在Linq To Sql自定义sql表达式中获取最后插入的id? [英] How to get the last inserted id in a Linq To Sql custom sql expression?
本文介绍了如何在Linq To Sql自定义sql表达式中获取最后插入的id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的问题. 我想在Linq To Sql中使用自定义sql表达式获取最后插入的ID.
Here is my problem. I'd like to get the last inserted Id with a custom sql expression in Linq To Sql.
我的插入方法:
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或其他方法).
lastId always returns null. When I tried this query (Insert + Select) directly in Sql Server, it works perfectly and returns the last inserted Id. I don't want to use a procedure and I can't use a new Product object (it is not possible for me to use InsertOnSubmit or whatever).
你能帮我吗? 谢谢.
推荐答案
好,我已经找到了解决方法:
Ok I've found how to do it:
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;
}
这篇关于如何在Linq To Sql自定义sql表达式中获取最后插入的id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文