switched from @@identity to scope_identity() for inserts, because of triggers #185

Closed
wants to merge 2 commits into
from
View
@@ -221,7 +221,7 @@ public class DynamicModel : DynamicObject {
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
- DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
+ public DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
var result = _factory.CreateCommand();
result.Connection = conn;
result.CommandText = sql;
@@ -267,10 +267,13 @@ public class DynamicModel : DynamicObject {
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands) {
+ var list = commands.ToList();
+ if (list.Count == 0) return 0;
+
var result = 0;
using (var conn = OpenConnection()) {
using (var tx = conn.BeginTransaction()) {
- foreach (var cmd in commands) {
+ foreach (var cmd in list) {
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
@@ -502,9 +505,8 @@ private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", s
if (BeforeSave(ex)) {
using (dynamic conn = OpenConnection()) {
var cmd = CreateInsertCommand(ex);
+ cmd.CommandText = cmd.CommandText + ";SELECT SCOPE_IDENTITY() as newID";
@zvolkov
zvolkov Jan 24, 2013 Contributor

SCOPE_IDENTITY must be executed as part of the same batch, otherwise it won't see the ID -- that's why I'm appending it to the same command as opposed to running separately

cmd.Connection = conn;
- cmd.ExecuteNonQuery();
- cmd.CommandText = "SELECT @@IDENTITY as newID";
ex.ID = cmd.ExecuteScalar();
Inserted(ex);
}
@@ -670,4 +672,4 @@ private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", s
return true;
}
}
-}
+}