John
John

Reputation: 68

DbContext not saving changes it shows it has

The goal is simple. I need to update the LastUpdated column in the Schedule table. I've tried several different methods to achieve that goal but with no success. I'm certain the code is pointing to the correct database and I'm also checking the correct [local] database for the changes. When a break point is set on SaveChanges(), the code halts at that point. I can see that "db" contains the updated Date/Time information for the correct record. Yet, it does not save it to the database.

Having gone through Stack Overflow, I've tried some suggestions like using Attach and setting the Entity State [to Modified]. Neither of those suggestions worked. HasChanges returns false, even though I can see the change is applied to the context variable.

Also, the class this method is in contains other methods that have no problem accessing the database and doing some inserts. The below code is just three different attempts to give you an idea on how I'm trying to do it. Any suggestions would be greatly appreciated.

public static void UpdateLastUpdated(int scheduleId)
{
    using (var db = new MyContext())
    {
        var schedule = from s in db.Schedule where s.Id == scheduleId select s;
        schedule.FirstOrDefault().LastUpdated = DateTime.Now;
        db.SaveChanges();

        var schedule2 = db.Schedule.Find(scheduleId);
        schedule2.LastUpdated = DateTime.Now;;
        db.SaveChanges();

        var schedule3 = db.Schedule.Single(s => s.Id == scheduleId);
        schedule3.LastUpdated = DateTime.Now;
        db.SaveChanges();
    }
}

Upvotes: 0

Views: 1146

Answers (2)

John
John

Reputation: 68

So as it turns out, after a lot of trial and error... The issue was because the column was computed. I tried updating another column in the same table from that method and it worked fine. Then I did some research on computed columns and found that to be the problem. After removing the annotation, the code works fine. Now I just need to figure out how to get the default value set without the annotation.

Thank you to everyone who offered solutions and comments. Much appreciated!

Upvotes: 1

Maske
Maske

Reputation: 864

You must indicate the change

db.Entry(schedule3).State = EntityState.Modified;

or

db.Entry(schedule3).Property(x => x.LastUpdated).IsModified = true;

Upvotes: 1

Related Questions