EntityFramework force the update of an object

The Problem

You are trying to save some changes to an object.
Your code looks like the following:

    using (var context = new DbEntities())
    {
        Job job = context.Jobs.Find(jobId);

        if (job != null)
        {
            job.Processed = true;
            context.SaveChanges();
        }
    }

But the changes are not being saved

The Solution

Entity framework is not aware that the job object has been changed so you need to tell it, by adding line 8.

    using (var context = new DbEntities(_config))
    {
        Job job = context.Jobs.Find(jobId);

        if (job != null)
        {
            job.Processed = false;
            context.Entry(job).State = EntityState.Modified;
            context.SaveChanges();
        }
    }

Note if you wish to control a specific propety and flag that only 1 columns has change

    context.Entry(job).Property("Processed").IsModified = true;

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.