0

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

这是我从 db 读取记录并将它们放入 BlockingCollection 的方法:

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

    List<Product> pList = products.Take(10).ToList();

现在如何用新的上下文更新数据库中的那些记录?谢谢!

我尝试了以下方法,但失败了:

                SMEntities context = new SMEntities();
                Product p = outPipe.GetConsumingEnumerable().First();
                outContext.Products.Attach(p);
                outContext.SaveChanges();

它返回异常:IEntityChangeTracker 的多个实例无法引用对象

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

4

3 回答 3

1

所做的所有更改仅保留在当前上下文中。一旦处理完毕,您的所有更改也会在该上下文中消失。如果您有一个具有更改的本地实体,您可以将其附加到新上下文。

context_.Attach(yourContextObject);

之后只需打电话

context_.SaveChanges();
于 2013-03-12T07:53:50.733 回答
1

试试这个:

SMEntities newContext = new SMEntities();
foreach(var product in products)
{
   newContext.Attach(product);
   db.Entry(product).State = EntityState.Modified;
}
newContext.SaveChanges();
于 2013-03-12T08:21:49.967 回答
0

再次附加,或替代:在您的新上下文中再次获取它并更新它(ApplyCurrentValues)。另请参阅实体框架 4 - ApplyCurrentValues<TEntity> 与 ObjectStateManager.ChangeObjectState

于 2013-03-12T08:19:12.647 回答