2

I have a very simple web api method that looks like this:

    public void Put(Vehicle vehicle)
    {
        db.Entry(vehicle).State = EntityState.Modified;
        db.SaveChanges();
    }

All it does is updating the direct properties of the vehicle entity. This works fine like this. But I would now like to know which properties have actually changed? Is there a way to do this?

I probably could get the vehicle from the database first and then compare it to the modified vehicle. But maybe there is an easier way.

Thanks

4
  • You can even look into the change tracker to see what entities are set to, and do further things based on that like auditing... Commented Jul 7, 2015 at 15:00
  • context.ChangeTracker.Entries<ITrackedEntity>().Where(entry => entry.State == EntityState.Added) Commented Jul 7, 2015 at 15:03
  • as far as I can see this requires to get the vehicle from the db first: entityframeworktutorial.net/… Commented Jul 8, 2015 at 13:20
  • The change tracker is in memory so why would you go to the db, just read that tutorial and it doesnt say that at all..... Commented Jul 8, 2015 at 14:30

2 Answers 2

1

Look at this

DbContext.Entry(vehicle).OriginalValues

And compare these values with your input vehicle

Sign up to request clarification or add additional context in comments.

2 Comments

this doesn't seem to work, Original and CurrentValues are the same
They are the same after serialization on database.
0
db.Entry(vehicle).GetDatabaseValues()

I found this and it seems to work. Now I just need to compare them

2 Comments

"I probably could get the vehicle from the database first and then compare it to the modified vehicle. But maybe there is an easier way." :)
yes but on a second thought it's probably impossible to do it without getting the vehicle from the db. EF will just write an update query with all the fields that are not PK. So from that update query there is no chance to know what has changed...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.