0

I read record from database and dispose ObjectContext associated with it. Later on when consumer finished with record I need to update it in db. How can do it with new context?

Here is how I read records from db and put them into BlockingCollection:

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

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

Now how to update those record in database with new context? Thanks!

I tried the following, but failed:

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

It returns with an Exception: object cannot be referenced by multiple instances of IEntityChangeTracker

UPDATE (explanation why I do not want to use the same context): Product record are consumed by many tasks in different threads and I won't call context.SaveChanges in producer thread, as some of the record in threads may be in the middle of setting changes to the Product record. What will happen in this case?

0

3 Answers 3

1

Try this:

SMEntities newContext = new SMEntities();
foreach(var product in products)
{
   newContext.Attach(product);
   db.Entry(product).State = EntityState.Modified;
}
newContext.SaveChanges();
Sign up to request clarification or add additional context in comments.

Comments

1

All changes done are only held in the current context. Once it is disposed, all your changes are also gone within that context. If you have a local entity with changes you can attach it to the new context.

context_.Attach(yourContextObject);

Afterwards just call

context_.SaveChanges();

Comments

0

Attach again, or alternative: Fetch it again in your new context and update it then (ApplyCurrentValues). See also Entity Framework 4 - ApplyCurrentValues<TEntity> vs. ObjectStateManager.ChangeObjectState

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.