2

ID列のあるテーブルがあります。
このようなコードでMassiveを使用する

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

それから

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

DBNullを返します:(

実際に挿入されたID値を取得するには、何を変える必要がありますか

4

1 に答える 1

5

The MSDN documentation states that SCOPE_IDENTITY:

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

Looking at the Massive source code, it appears that every call to Scalar() opens a new connection:

/// <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;
}

Therefore, every time you are doing table.Scalar("select scope_identity()"); you are actually doing this in a new connection (which means a different session/scope).

This explains the DBNull result.

But since you are already doing:

var newID = table.Insert(...)

you might want to inspect the value of newID after the insert happens; I hope you'll find something nice in there.

At least, that's what the code for Insert() leads me to believe:

   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;
        }
    }
于 2013-02-25T20:42:29.630 に答える