0

假设我有一个类似这样的代码;

using (DAL.MyContext db = new DAL.MyContext())
{
   foreach (var item in UpdatedValues)
   {
      try
      {
          switch (item.Status)
          {
                case Enums.Status.Delete:
                   //stuff
                   break;
                case Enums.Status.Updated:
                   //stuff
                   break;
                case Enums.Status.Added:
                   //stuff
                   break;
          }

          db.SaveChange(); //crashing here
      }
      catch(Exception ex)
      {
         tools.log(ex);
         /*
              how to remove the last action so the for each can continue?
         */
      }
   }
}

我想从上下文中删除最后的更改。

为什么?

如果有异常,下一个更改也会抛出异常,因为最后一个没有工作,但仍然在“上下文”中,所以它会再次尝试保存。

那可能吗?

4

2 回答 2

0

unless someone find this not "proper" this seem to fix my issue;

in the catch, after looking at System.Data.Entity.Internal.InternalEntityEntry.State version 5.0 with ILSpy, all I need is

    internal static void UndoContextChange(DB_Context db)
    {
        foreach (var item in db.ChangeTracker.Entries())
        {
            if (item.State == System.Data.EntityState.Modified)
            {
                item.State = System.Data.EntityState.Unchanged;
            }
            else if (item.State == System.Data.EntityState.Deleted)
            {
                item.State = System.Data.EntityState.Unchanged;
                item.CurrentValues.SetValues(item.OriginalValues); //just in case
            }
            else if (item.State == System.Data.EntityState.Added)
            {
                item.State = System.Data.EntityState.Detached;
            }
        }        
    }
于 2013-06-27T13:51:01.787 回答
0

没有 Detach 方法 :-( 但是可以更改实体状态 请参阅枚举....

// Type: System.Data.EntityState
public enum EntityState
{
Detached = 1,
Unchanged = 2,
Added = 4,
Deleted = 8,
Modified = 16,
}

//See
Context.Entry(poco).State = state;

否则只需更新上下文。无论如何,通常是更好的方法。

于 2013-06-27T13:53:47.860 回答