C# 更新数据库中的记录

C# 更新数据库中的记录,c#,entity-framework,.net-4.0,C#,Entity Framework,.net 4.0,我从数据库中读取记录并处理与其关联的ObjectContext。 稍后当消费者完成记录时,我需要在db中更新它。 如何在新的环境下做到这一点 以下是我如何从db中读取记录并将其放入BlockingCollection中: var products = from r in context_.Products orderby r.id

我从数据库中读取记录并处理与其关联的ObjectContext。 稍后当消费者完成记录时,我需要在db中更新它。 如何在新的环境下做到这一点

以下是我如何从db中读取记录并将其放入BlockingCollection中:

    var products = from r in context_.Products                                   
                               orderby r.id
                               select r;

    List<Product> pList = products.Take(10).ToList();
它返回一个异常:对象不能被多个IEntityChangeTracker实例引用

更新(解释为什么我不想使用相同的上下文):
产品记录被不同线程中的许多任务所消耗,我不会调用生产者线程中的Exchange。SaveCurviod,因为线程中的某些记录可能处于对产品记录进行设置更改的中间。在这种情况下会发生什么

所做的所有更改仅在当前上下文中保留。一旦它被释放,您的所有更改也都会在该上下文中消失。如果您有一个带有更改的本地实体,则可以将其附加到新上下文

context_.Attach(yourContextObject);
之后就给我打电话

context_.SaveChanges();

再次附加或替换:在新上下文中再次获取它,然后更新它(ApplyCurrentValues)。另请参见尝试以下操作:

SMEntities newContext = new SMEntities();
foreach(var product in products)
{
   newContext.Attach(product);
   db.Entry(product).State = EntityState.Modified;
}
newContext.SaveChanges();
SMEntities newContext = new SMEntities();
foreach(var product in products)
{
   newContext.Attach(product);
   db.Entry(product).State = EntityState.Modified;
}
newContext.SaveChanges();