0

假设我的表中有一行:

| ID | Name       |
|  1 | file1.doc  |

我想更新该行中的 Name 列,所以我使用该代码:

public partial class Adapter
{
    private my_Entities _db = null;

    public my_Entities db
    {
        get
        {
            if (_db == null) _db = new my_Entities();
            return _db;
        }
    }

    public Orders GetOrderByID(int id)
    {
        return (from x in db.Orders
                where x.ID == id
                select x).FirstOrDefault();
    }
 }

 Adapter adapter = new Adapter();

 var order = adapter.GetPublishOrderByID(123);

 for(int i = 0; i < 2; i++) //< 2 is just for test, the purpose of the whole code is to append the FileName if any file exist for the order
 {
    var existingFile = order.Files.FirstOrDefault();

   //here I get the information about entries
   var objectStateEntries = adapter.db.ObjectStateManager.
                         GetObjectStateEntries(EntityState.Added | 
                                               EntityState.Modified | 
                                               EntityState.Unchanged);


   if (existingFile  != null)
   {
     //now, in the objectStateEntries I can see that ont item with the Added state,
     //and the another entity with the Modified state.
     //They're poining at the same entity (the same ID)

      existingFile.FileName = "lorem.doc";   //FileName is 'file1.doc'    
   }
   else
   {
      order.P_CoverOptionalTempFiles.Add(new P_Files{ FileName = "file1.doc" });
      //the row's State is Added
   }

   adapter.db.SaveChanges();
}

现在在我的数据库中我看到两行

| ID | Name       |
|  1 | file1.doc  |
|  2 | lorem.doc  |

为什么 ?

4

1 回答 1

0

解决方案是,我必须动态创建上下文。以后知道就好了。但我仍然想知道为什么前面的代码会导致这个问题......

var order = adapter.GetPublishOrderByID(123);

for(int i = 0; i < 2; i++)
{
   using(my_Entities ctx = new my_Entities)
   {
        //now, instead of the adapter.db I use ctx
   }
}
于 2012-08-16T22:33:46.213 回答