Entity Framework Pass Object from One Context to Another

c# entity-framework multithreading

Question

I am new to Entity Framework so please bear with me.

I have a program that I want to select multiple records from a table and store it in a queue:

private Queue<RecordsToProcess> getRecordsToProcess()
{
    Queue<RecordsToProcess> results = new Queue<RecordsToProcess>();
    using (MyEntity context = new MyEntity())
    {
        var query = from v in context.RecordsToProcess
                            where v.Processed == false
                            select v;

        foreach (RecordsToProcess record in query)
        {
            results.Enqueue(record);
        }
    }
}

Then I spin up multiple worker threads. Each worker thread takes one of the items in queue, processes it, and then saves it to the database.

private void processWorkerThread(object stateInfo)
{
    while (workQueue.Count > 0)
    {
        RecordToProcess record = new RecordToProcess;
        lock(workQueue)
        {
            if (workQueue.Count > 0)
                RecordToProcess = workQueue.Dequeue();
            else
                break;
        }

        //Do the record processing here

        //How do I save that record here???
    }
}

My understanding is that to save changes back to the database you just call context.SaveChanges() but I can't do that in this situation can I?

Any help is appreciated.

Thanks!

1
13
1/28/2013 10:22:47 PM

Accepted Answer

Since you are disposing your MyEntity context in the first method (by wrapping it in a using statement), the entities that are enqueued will be in a "detached" state. That means, among other things, that changes done to the entity will not be tracked and you will not be able to lazy load navigation properties.

It is perfectly fine to dequeue these entities, "attaching" them to a different context, update them, and then call SaveChanges to persist the changes.

You can read about Attaching and Detaching Objects and Add/Attach and Entity States

11
3/13/2018 12:20:06 PM

Popular Answer

It might be safer if you save off the primary key in the queue instead and retrieve the entities again. This way you are more likely avoid any data concurrency issues.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow