如何执行插入到数据库并使用Dapper返回插入的身份?
我已经尝试过这样的事情:
string sql = "DECLARE @ID int; " +
"INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); " +
"SELECT @ID = SCOPE_IDENTITY()";
var id = connection.Query<int>(sql, new { Stuff = mystuff}).First();
但这没有用。
@Marc Gravell谢谢您的答复。我已经尝试过您的解决方案,但是下面仍然有相同的异常跟踪
System.InvalidCastException: Specified cast is not valid
at Dapper.SqlMapper.<QueryInternal>d__a`1.MoveNext() in (snip)\Dapper\SqlMapper.cs:line 610
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in (snip)\Dapper\SqlMapper.cs:line 538
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param) in (snip)\Dapper\SqlMapper.cs:line 456
numeric
,是吗?也许使用您的原始代码和select @id
?(这只是添加了一个强制转换)。我将做笔记以确保在将来的dapper版本中自动运行。现在的另一个选择是select cast(SCOPE_IDENTITY() as int)
-再次丑陋。我会解决这个问题。