I have the following code:
model = new Option();
model.val1 = newVal1;
model.val2 = newVal2;
model.val3 = newVal3;
//this saves new record just fine
if (recordCount < 1)
{
context.Options.AddObject(model);
context.SaveChanges();
}
else
{
var tempID = from s in context.Options where (s.val1 == newVal1 && s.val2 == newVal2) select s.ID;
var resultsID = tempID.First();
model = context.Options.Single(m => m.ID == resultsID);
if (TryUpdateModel(model, new[] { "val3" }))
{
//this isn't updating the record
context.SaveChanges();
}
}
The database adds a new entry just fine, but isn’t updating it. What am I missing? Thanks.
Looking at this code, you first make a new model and set some properties on it:
then, assuming you’re heading down the “else” path you do this:
which goes out and finds the entry in
context.Optionsthat has the matching ID.So, now that
model, which you created via thenew()call (which I’ve marked with the comment “A”) is now cast adrift and you’ve got a different one – the one you retrieved via the call tocontext.Options.Single(), which I’ve marked with the comment “B”. It has properties based on what’s in the context, not what was in that object you made. That A object is gone now. You’ve got a new object, B, retrieved from the DB.So now, you’re calling TryUpdateModel on this retrieved object, telling it that val3 is updated, but the value hasn’t changed, right? It’s whatever you pulled from the context.
So, it’s not going to update anything because the model object isn’t the one you think it is… the one you updated is waiting to be garbage collected. The one you retrieved hasn’t been updated because it still has whatever value it’s got for the property
val3.Assuming I follow what you’re trying to do here, that’s why you’re not seeing any updated values in the context.
If you want to change the value of the
val3property on thatmodelobject you’ve retrieved, you need to set it after you retrieve it, otherwise it is overwritten.