I'm having a problem with Entity Framework while trying to update a specific record The error message says "The property 'ID' is a part of the object key information and cannot be modified". My table has a primary key and I'm not trying to update the Id. Here is the method
public void SetAsDefaultImage()
{
int id = Convert.ToInt32(Request.QueryString["id"].ToString());
int pid = (int)TempData["ImgProductId"];
Images defaultImage = Context.Connection.Images.FirstOrDefault(x => x.Default == true && x.ProductID==pid);
defaultImage.Default = false;
UpdateModel(defaultImage);
int result=Context.Connection.SaveChanges();
if (result > 0)
{
Images setdefault = Context.Connection.Images.First(x => x.Id == id);
setdefault.Default = true;
UpdateModel(setdefault);
Context.Connection.SaveChanges();
}
}
Any idea on what might be causing this error?
CodePudding user response:
since you are changing two records, it is better to use this code
var defaultImage = Context.Connection.Images.FirstOrDefault(x => x.Default == true && x.ProductID==pid);
defaultImage.Default = false;
var setdefault = Context.Connection.Images.First(x => x.Id == id);
setdefault.Default = true;
Context.Connection.SaveChanges();
CodePudding user response:
The problem is caused by the call to the MVC method UpdateModel
From what I understand UpdateModel is not usually required. It comes handy when you don't pass the Model to the controller and want to create yourself a model instance and want it populated with the Controller IValueProvider.
The overload you called will try to populate every property from the Controller IValueProvider and probably this will update the ID property. There are other overloads of UpdateModel that makes more sense like the ones that let you specify the list of properties that you want to be updated.
At the end you can simply remove the two calls to UpdateModel and the code should work as expected. Some other information can be retrieved by this blog article.