Search code examples
entity-frameworkbackgroundworker

How to properly use Object Contexts in Entity Framework using BackgroundWorker


I am developing using Entity Framework and WPF, and I am encountering some errors and I don't know why. When saving a record (using a BackgroundWorker), I set the entities change tracker to nothing (null), attach the record to a new disposable context, save it, detach, and dispose of the context.

Saving a record fires and event in theMainViewModel of the program that the other ViewModels (including the one that is saving) need to refresh their entities to reflect changes.

Private Sub _saveRecordWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles _saveRecordWorker.DoWork
    Using MyContext As New RVShippingEntities
        Dim MyShipment = CType(ShipmentRecord, IEntityWithChangeTracker)
        MyShipment.SetChangeTracker(Nothing)
        MyContext.Attach(MyShipment)
        MyContext.Detach(ShipmentRecord)
    End Using
End Sub

The Refresh background worker is similar, but it has a Do While block to keep it from interfering with the save worker (which doesn't appear to be working; hence the post). When I save (and it subsequently refreshes) I get the following error: The calling thread cannot access this object because a different thread owns it.

I thought that with theDoWhile block, it would wait (and when I step through it does) until the save thread finished, and all would be good. But it would seem that something (either the main thread or the save thread) is still doing something that is interfering.

Is there a better way of doing this? Am I doing it in a goofy kludgey fashion? Any help would be appreciated.

(Apparently Firefox recognized kludgey as a word. Interesting)


Solution

  • So, 3+ months and nary an exception so far in relation to Entity Framework. I am going to call this the answer.

    Parent Views (in my case Company, Customer, Shipment) have a context which is passed to child Views as necessary (Addresses, Phone Nums, Email Addresses, for Company and Customer; Packages, Contents, for Shipments). Anytime a context can't save changes or what have you (db disconnection is most common cause), the context is disposed, a new one instanced, the entities are re-attached, set to modified (based on custom change tracking which I do for UI), and changes are saved.