justacodemonkey
justacodemonkey

Reputation: 620

EntityFramework 4 - Updating records in foreach

I am creating an app which is using EF4 and DBContext to access the backend database.

At one point in the application I pull back a set of records and iterate them, updating the value and a timestamp.

Code:

// update any notified parameters...
foreach (RecvParam parameter in RecvParameters)
{
    // get the existing parameter
    Data.DeviceParameter dbParameter = this.device.DeviceParameters.SingleOrDefault(x => x.Name == parameter.Name);

    // null check
    if (dbParameter == null)
        continue;

    // update an existing parameter instance
    dbParameter.Value = parameter.Value;
    dbParameter.UpdatedOn = DateTime.Now;

    // add an entry to the context
    DBContext.Entry(dbParameter).State = EntityState.Modified;        
}

DBContext.SaveChanges();

When I do this, my database values do not change... the timestamps and value fields stay the same.

Could someone possibly point me in the right direction...?

Upvotes: 0

Views: 1790

Answers (1)

ken2k
ken2k

Reputation: 48975

Actually it's not required to update the state of your entities manually. Modifying a property of an entity that is attached to a context does the job for you.

Anyway, if device is your database context, you must call SaveChanges on it.

Upvotes: 2

Related Questions