MaT
MaT

Reputation: 1606

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 !

Upvotes: 7

Views: 6179

Answers (5)

Damith Asanka
Damith Asanka

Reputation: 964

If you want to get old value and new value separate :

 //user.UserName = "oldtest"     
 user.UserName = "Test"     
 var originalValues = db.Entry(user).OriginalValues.Clone();
 var originalval = originalValues.GetValue<string>("UserName");
 var currentvalue = db.Entry(user).CurrentValues.Clone();
 var curretval = currentvalue.GetValue<string>("UserName");

This will return originalval as old value before set new UserName as "oldtest" and curretval return new UserName as "Test"

Upvotes: 0

Stack crashed
Stack crashed

Reputation: 220

Adding on to the lkaradashkov's answer. You can try using the option AsNoTracking() to prevent Entity Framework from tracking it.

public ActionResult Edit(User user)
{
    User oldUser = db.Users.AsNoTracking().Single(x=>x.id.equals(user.id));
    // oldUser object represents the user before the modification
    ...
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

Upvotes: 0

context.Entry(YourEntity).GetDatabaseValues().ToObject() as YourEntity

Upvotes: 2

MaT
MaT

Reputation: 1606

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();

Upvotes: 12

lkaradashkov
lkaradashkov

Reputation: 8899

How about this:

public ActionResult Edit(User user)
{
    User oldUser = db.Users.Find(user.id);
    // oldUser object represents the user before the modification
    ...
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

Upvotes: 0

Related Questions