实体框架 - 在更新后插入新行

时间:2012-08-16 19:53:25

标签: entity-framework

让我说我的桌子上有一排:

| 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  |

为什么?

1 个答案:

答案 0 :(得分: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
   }
}