Kénium
Kénium

Reputation: 105

Is there a better way to get an older value after an EntityState.Modified in EF5?

I just want to know if it existe a better way to get the value in database after an EntityState.Modified. My syntaxe :

db.Entry(UserProfile).State = EntityState.Modified;
var olderPhoto = (string)db.Entry(UserProfile).GetDatabaseValues()["Photo"];

Thank you for an eventually answer

Upvotes: 1

Views: 145

Answers (2)

Amin Saqi
Amin Saqi

Reputation: 18977

I think there is...:

db.Entry(UserProfile).State = EntityState.Modified;
var olderPhoto = db.Users.Find(UserProfile.UserID).Photo.ToString();

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239460

Well, depends. If you have no control over when the entity is being modified and you want to be able to get the old value after it's been modified (but presumably before it's been committed), then that's pretty much your only resort: fetch it fresh from the database.

However, if you can simply store the original somewhere before you modify it, then you can just use that without having to requery the database. The catch here is that you must explicitly store any and all values you need into a variable(s), just storing the entity itself would only store the pointer to the same instance.

var olderPhoto = UserProfile.Photo;

UserProfile.Photo = newPhoto;
db.Entry(UserProfile).State = EntityState.Modified;

// use olderPhoto

Upvotes: 1

Related Questions