Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Pass Object from One Context to Another

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!

like image 302
jkruer01 Avatar asked Jan 28 '13 22:01

jkruer01


2 Answers

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

like image 53
khellang Avatar answered Oct 21 '22 21:10

khellang


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.

like image 42
Sacrilege Avatar answered Oct 21 '22 22:10

Sacrilege