gpt4 book ai didi

sql - 使用 Massive Insert 我在尝试获取 scope_identity() 时得到 DBNull

转载 作者:行者123 更新时间:2023-12-02 22:12:11 26 4
gpt4 key购买 nike

我有一个带有标识列的表。
通过这样的代码使用 Massive

var table = new Categories();
var newID = table.Insert(new {CategoryName = "Buck Fify Stuff", Description = "Things I like"});

然后

table.Scalar("select scope_identity()");

返回 DBNull :(

我需要做些什么来获取实际插入的标识值

最佳答案

MSDN 文档指出 SCOPE_IDENTITY :

"retrieves the last identity values that are generated in any table in the current session"

查看 Massive source code ,似乎每次调用 Scalar() 都会打开一个新连接:

/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args) {
object result = null;
using (var conn = OpenConnection()) { // <-- see this ...
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}

...

/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection() {
var result = _factory.CreateConnection();
result.ConnectionString = ConnectionString;
result.Open(); // <-- ...and this
return result;
}

因此,每次您执行 table.Scalar("select scope_identity()"); 您实际上是在一个新的连接中执行此操作(这意味着不同的 session /范围)。

这解释了 DBNull 结果。

但是既然你已经在做:

var newID = table.Insert(...)

您可能想在插入发生后检查 newID 的值;我希望你会在那里找到一些不错的东西。

至少,Insert() 的代码让我相信:

   public virtual dynamic Insert(object o) {
var ex = o.ToExpando();
if (!IsValid(ex)) {
throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray()));
}
if (BeforeSave(ex)) {
using (dynamic conn = OpenConnection()) {
var cmd = CreateInsertCommand(ex);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY as newID";
ex.ID = cmd.ExecuteScalar();
Inserted(ex);
}
return ex;
} else {
return null;
}
}

关于sql - 使用 Massive Insert 我在尝试获取 scope_identity() 时得到 DBNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15075913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com