Entity Framework Update check if the record has changed

Viewed 14137

I am updating a database table using EF.

Its a simple scenario in connected mode.

I get the row I want to update

var order = from o in Orders
        where o.ID = 1
        select o;

I then update the record as:

order.FirstName = "First";
order.LastName = "Last";
context.SaveChanges();

It works fine. EF checks if the field has changed and only updates the field if its a new value. I have enabled CDC on my SQL server to check that EF does not rewrite to the database if the value has not changed.

Now I want to put this check in my code for additional logic i.e. I want EF to tell me when the record was updated, and when it was not (because the value has not changed). Can anyone please tell if there is a way?

I do not want to manually check each field as I have a lot of fields to compare.

Thanks

2 Answers

I came across this question/answer when I was looking for something similar if not the same thing. I ended up using this approach which seems to work alright for me.

var order = from o in context.Orders
        where o.ID = 1
        select o;

order.FirstName = "First";
order.LastName = "Last";

if (context.Entry(order).State != EntityState.Unchanged)
{
    // order has changed ...
}

So posting what worked for me in case it might be helpful for others who come here looking for something similar.

Related