Block entity frame code while updating the database

I have a property Statethat, during installation, updates the entity in the database.

The problem is that this property is set through several threads , and sometimes the task field is simultaneously bound to two contexts, which leads to the following exception:

An entity object cannot reference multiple instances of IEntityChangeTracker.

I tried using a lock around the statement using, but this does not work:

private Job job;

public string State 
{
    get
    {
        return job.State;
    }
    set
    {
        lock (job)
        {
            using (MyEntities context = new MyEntities())
            {
                context.Jobs.Attach(job);
                job.State = value;

                context.SaveChanges();
            }
        }
    }
}

What is the best way to do this?

+4
source share
2

, :

lock (job)
{
     using (MyEntities context = new MyEntities())
     {
           context.Jobs.Attach(job);
           job.State = value;
           context.SaveChanges();
           context.Detach(job);  // Detach the object
      }
}

UPDATE:

, . , job , . job , , http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx

+1

, job . , .

object :

private Job job;

private static object jobInstanceLock;

public string State 
{
    get
    {
        return job.State;
    }
    set
    {
        lock (jobInstanceLock)
        {
            using (MyEntities context = new MyEntities())
            {
                context.Jobs.Attach(job);
                job.State = value;

                context.SaveChanges();
            }
        }
    }
}
0

All Articles