Entity Framework: Using transactions and rollbacks… Possible?

后端 未结 3 1758
天命终不由人
天命终不由人 2020-12-13 15:08

Issue: (With Sql 2005)

  • How can I query the database while the transaction is up? (Since it locks the table)
  • How can cause a t
3条回答
  •  孤街浪徒
    2020-12-13 15:32

    In my case I delete all records from a Table through plain SQL since EF doesn't provide a functionality for this. After that I add some new entities - but when it fails, the table shouldn't be empty. The use of MSDTC (TransactionScope) seems not possible for me. I reduced the transaction to the DB:

    My code:

    using (var transaction = context.Connection.BeginTransaction())
    {
          // delete all
          base.DeleteAll(context);
    
          // add all
          foreach (var item in items)
          {
               context.TESTEntity.AddObject(item);
          }
    
          try
          {
               context.SaveChanges();
               transaction.Commit();
               return true;
          }
          catch (Exception ex)
          {
               Logger.Write("Error in Save: " + ex, "Error");
               transaction.Rollback();
               return false;
          }
    }
    

    And here the helper functions

        protected void DeleteAll(ObjectContext context) where TEntity : class
        {
            string tableName = GetTableName(context);
            int rc = context.ExecuteStoreCommand(string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}", tableName));
        }
    
        protected string GetTableName(ObjectContext context) where TEntity : class
        {
            string snippet = "FROM [dbo].[";
    
            string sql = context.CreateObjectSet().ToTraceString();
            string sqlFirstPart = sql.Substring(sql.IndexOf(snippet) + snippet.Length);
            string tableName = sqlFirstPart.Substring(0, sqlFirstPart.IndexOf("]"));
            return tableName;
        }
    

提交回复
热议问题