I’m implementing a Producer / Consumer pattern:
Producer
- Materializes objects from DB based on search criteria
- Applies additional application-specific filtering logic
- Queues materialized objects for further processing
Consumer (Multiple threads)
- Receives materialized objects from queue
- Populates email template using data from materialized object
- Updates the materialized object state
- Saves new object state to the DB
The Issue
The objects are materialized using Entity Framework Code First using a context associated with the producer thread.
The consumer threads require their own context.
Is it possible to move the materialized objects (each object is really an object graph) from the producer context to the consumer context, or must I rematerialize the object in the consumer’s context in order to update it there? How can I do the move?
I think what you want is the following:
Entity framework allows you to re-attach an object to the contexts tracking graph and treat it as the current state of the object in the database. This means it will only update the properties you touch in your update block.
Ie you want to follow this update without prior select path for updates:
Whats important to note about this method is that you can only attach an entity (defined by a unique key) to the tracking graph once. So its really important to do this on an isolated context or to carefully manage the attach call.