How to properly use Object Contexts in Entity Framework using BackgroundWorker

Posted by OffApps Cory on Stack Overflow See other posts from Stack Overflow or by OffApps Cory
Published on 2010-05-25T18:04:08Z Indexed on 2010/05/25 18:11 UTC
Read the original article Hit count: 265

Good day,

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 the MainViewModel 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 the DoWhile 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 is a goofy kludgey fashion? Any help would be appreciated.

(Apparently Firefox recognized kludgey as a word. Interesting)

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about backgroundworker