Multithreading with Entities RRS feed

  • Question

  • Hello,

    I am using Entity Framework v1 (.NET 3.5 SP1).

    I have two entities called Job and Event.
    A Job can have several Events, and the foreign key mechanism is translated to a Job.Events property of type EntityCollection<Event>.
    New items are added to the Job.Events collection regularly, and that can last for an indeterminate amount of time. At some point, this needs to be persisted, without interrupting the addition of entities to the Job.Events collection.

    My problem is: Multithreading needs to be used to achieve what I want, but I cannot just add the Job to an ObjectContext and call SaveChanges every now and again. Events keep being added to the context while it is saving without any thread safety... smells so much like a disaster waiting to happen that I won't even try.

    My question is: So how do I do it?

    Perhaps ideally there would be way of adding Events to the EntityCollection in a detached state so that they are ignored, and then, synchronously with the upcoming SaveChanges, switch batches of them to an added state, for persistence. But after looking everywhere, I have not found any way of doing that, and I'm not even sure it's a good idea anyway.

    Currently I see 2 options :
    - Remove the Job.Events property and use ID properties, along with a Dictionary<Job, IList<Event>> to keep a link between a Job and its Events in memory. I'd unfortunately be losing part of the convenient mechanisms of EF.
    - Never add/attach those entities, but clone them, add/attach the clones, and, after the insertion of a new Job, update the original Job's EntityKey for future attachment. But that really has a "hack" feeling to it.

    Is there an obvious pattern which I'm missing that could provide an elegant solution to this problem? If not, which of the above 2 solutions (or some variant) would be preferable?

    Thanks for your time

    • Edited by antbj Thursday, November 26, 2009 12:38 AM wrong entity name
    Thursday, November 26, 2009 12:37 AM