Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access old entity value in ASP.NET Entity Framework

I have a small ASP.Net mvc3 application and I am on the edit part. I have the default template:

public ActionResult Edit(int id)
{
    User user = db.Users.Find(id); 
    return View(user);
}

public ActionResult Edit(User user)
{
    //(Here access to old user name for example)
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

If i do user.name I have the new value but I want to access the db value before the save.

Thanks !

like image 701
MaT Avatar asked Jun 07 '12 17:06

MaT


People also ask

How do I get my ID after SaveChanges?

Now, when you add a new Student and call SaveChanges() method, EF will assign a newly generated id to the StudentID property. EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope.


1 Answers

I got it work with a small trick:

db.Users.Attach(user);
var current = db.Entry(user).CurrentValues.Clone();
db.Entry(user).Reload();
//Do you user(from db) stuff
db.Entry(user).CurrentValues.SetValues(current);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
like image 93
MaT Avatar answered Sep 20 '22 13:09

MaT