Share This!

Thursday, April 21, 2016

MVC: Comparing old values to postback

I wanted to compare a couple values to their previous values on postback (Edit) to do some special processing.


So rather than put hidden fields on the page with the old values, why not just load the record on postback and do my checking there?  Easy peasy!


Assignment oldAssignment = db.Assignments.Find(assignment.UniqueID);

... then I can make my comparisons:
bool statusBarChg = (CompanyStatusBarSelectList != oldAssignment.StatusBarID);
bool dspChg = (assignment.DSPID != oldAssignment.DSPID);

The only problem is that when I get to my Save(), I get this:
Attaching an entity of type [MODEL] failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Apparently, Entity Framework thought that my oldAssignment was blocking the assignment object from the postback.  The solution is simple: change this:

Assignment oldAssignment = db.Assignments.Find(assignment.UniqueID);

…to this:
Assignment oldAssignment = db.Assignments.AsNoTracking().Where(d => d.UniqueID == assignment.UniqueID).FirstOrDefault();

The .AsNoTracking() makes it so the oldAssignment loads the old values without telling Entity Framework that it owns the record in the table.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *