Quick background: I am trying to write an Edit HttpPost Action.
public async Task<ActionResult> Edit (myViewModel model){
if(ModelState.IsValid){
myObject x = await db.myObjects.FindAsync(model.Id);
db.Entry(x).State = EntityState.Modified;
// code to map model to x
await db.SaveChangesAsync();
//...
The SaveChangesAsync() line gives an error: "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Now the weird part: When I add lines such as
Console.Write(x.property1);
Console.Write(x.property2.name);
etc. for all the properties of x, then do the mapping from model to x and then savechanges, the error does not occur and the code behaves as I expect it to.
Please help, thank you.
EDIT: EntityValidationErrors say x.prop1 and x.prop2 are required. Another fix I discovered: writing x.prop1 = x.prop1; before db.SaveChangesAsync(); Feels weird but it is working.
EDIT 2: My code in detail:
public class myObject{
public int Id {get; set;}
[Required]
public virtual y prop1 {get; set;}
[Required]
public virtual z prop2 {get; set;}
[Required]
public string prop3 {get; set;}
[Required]
public string prop4 {get; set;}
}
And here is the mapping code:
if(ModeState.IsValid){
myObject x = await db.myObjects.FindAsync(model.Id);
db.Entry(x).State = EntityState.Modified;
x.prop3 = model.editedValueForProp3;
db.myObjects.AddOrUpdate(x);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
Things to note: I only get validation errors for prop1 and prop2 which are virtual properties. The errors disappear if I write these lines before db.SaveChangesAsync()
x.prop1 = x.prop1;
x.prop2 = x.prop2;
I am using lazy loading. Could that be the problem?