MVC's UpdateModel acting strange and reverting values. Why?
I have an object that I am trying to update using MVC(2), also using EntityFramework framework.
I know I haven't provided much code but don't really feel it necessary. The reason I have logic like this, i'll explain:
- I have some cascading drop downs, and when one of the drop downs is empty I use jQuery to fill it with an "UNKNOWN" value e.g. with id like -1.
- So when I get value -1, I create the UNKNOWN value which is in another table.
- Then I find that object and assign it to
Fruit
Code like this:
if (id == -1)
{
//The object was unknown so create it
var newUnknown = new Fruit
{
Name = "UNKNOWN";
};
EntityFramework.AddToFruits(newUnknown);
EntityFramework.SaveChanges();
defaultValueObject = EntityFramework.Fruits.Single(x=>x.FruitID == newUnknown.FruitID);
object.Fruit = defaultValueObject;
object.Date = DateTime.Now;
UpdateModel(object);
EntityFramework.SaveChanges();
After UpdateModel(object);
line is run, the value I set in, for example, Fruit
reverts to what was sent over from the form... (which is -1) and then EntityFramework.SaveChanges();
fails FK con开发者_如何学JAVAtrainst (because fruit with id -1 doesn't exist)! Fair enough - but that's not what I assigned to you!
I don't understand why it reverts, because after the first AddToFruits()
the unknown is in the database fine... and all up untill UpdateModel(object);
it is in object
...
If it adds it like I have assigned it there will be no FK contraint exception. But MVC's UpdateModel decides to do something strange and default to (perhaps what came over with form submission) and screws it up.
Why does this happen? How can I fix it?
UpdateModel is not doing anythign strange, it's doing what it's supposed to do; update an object with the values from the form submission.
EF is tracking changes, so it tries to update the db values with what the object has at the time of save.
Solve it by making your changes after running UpdateModel.
You can pass in an array of strings to UpdateModel to tell it what properties to update in your model.
public class Fruit
{
int ID { get; set; }
bool IsTasty { get; set; }
string MyOtherPropert { get; set; }
DateTime Date { get; set; }
}
...
if (id == -1)
{
//The object was unknown so create it
var newUnknown = new Fruit
{
Name = "UNKNOWN"
};
EntityFramework.AddToFruits (newUnknown);
EntityFramework.SaveChanges ();
defaultValueObject = EntityFramework.Fruits.Single (x=>x.FruitID == newUnknown.FruitID);
defaultValueObject.Date = DateTime.Now;
UpdateModel (object, new string[] { "IsTasty", "MyOtherProperty" });
EntityFramework.SaveChanges ();
}
Doing this will make sure all the properties you want updated will be, and those you want left alone won't be touched. In this case, ID and Date are going to be ignored by UpdateModel.
精彩评论