Entity Framework with WinForms : Best Practices with a BackgroundWorker RRS feed

  • Question

  • So, it sounds like the best way to go is to have the lifetime of the objectcontext be the same as the form.

    However googling has made clear the EF is not threadsafe and that I should "simply create a new objectcontext in the thread".

    How do I do this simply though? How do I hand the entities fetched in the thread by one objectcontext to the objectcontext that exists outside the thread?

    Seems like concurrency suddenly becomes a major headache at this point too.

    Am I missing something obvious?

    EDIT: I'm also using EF 5.x DbContext Generator for C#
    • Edited by Fenyx4 Tuesday, October 16, 2012 5:49 PM Additional info
    Tuesday, October 16, 2012 4:46 PM


  • Hi Fenyx4,

    Welcome to the MSDN forum.

    More than one thread operating on a single Entity Framework context is not thread safe. If you want to an outside DbContext to use the entities tracked by current DbContext, you are required to detach the entities then attach them to outside DbContext. Moreover, You could, for example, retrieve data on one thread by using `MergeOption.NoTracking`, and then divide the data into groups and hand it off to other threads that attach the entities to their own thread context, make updates, and then save.

    Have a nice day.

    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Alexander Sun Tuesday, October 23, 2012 9:05 AM
    Thursday, October 18, 2012 8:04 AM