我也在尝试更新实体及其相关实体。例如,我有一个具有属性类别的类Car,我想更改其类别。所以,我在Controller中有以下方法:
public ActionResult Edit(int id)
{
var categories = context.Categories.ToList();
ViewData["categories"] = new SelectList(categories, "Id", "Name");
var car = context.Cars.Where(c => c.Id == id).First();
return PartialView("Form", car);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Car car)
{
var category = context.Categories.Where(c => c.Id == car.Category.Id).First();
car.Category = category;
context.UpdateCar(car);
context.SaveChanges();
return RedirectToAction("Index");
}
ObjectContext类中的UpdateCar方法如下:
public void UpdateCar(Car car)
{
var attachedCar = Cars.Where(c => c.Id == car.Id).First();
ApplyItemUpdates(attachedCar, car);
}
private void ApplyItemUpdates(EntityObject originalItem, EntityObject updatedItem)
{
try
{
ApplyPropertyChanges(originalItem.EntityKey.EntitySetName, updatedItem);
ApplyReferencePropertyChanges(updatedItem, originalItem);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
}
public void ApplyReferencePropertyChanges(IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity)
{
foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds())
{
var oldRef = relatedEnd as EntityReference;
if (oldRef != null)
{
var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;
oldRef.EntityKey = newRef.EntityKey;
}
}
}
问题是当我在控制器中的POST之后设置Category属性时,实体状态将更改为Added而不是保留为Detached。
如何在不设置所有属性的情况下更新与Entity Framework和ASP.NET MVC的一对一关系,如this帖子一样?
答案 0 :(得分:1)
好的人,我刚刚发现它是如何解决的。不是在Category属性中设置整个对象,而是必须在引用属性中仅设置实体键。
所以,这是错误的:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Car car)
{
var category = context.Categories.Where(c => c.Id == car.Category.Id).First();
car.Category = category;
context.UpdateCar(car);
context.SaveChanges();
return RedirectToAction("Index");
}
这是正确的方法:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Car car)
{
var category = context.Categories.Where(c => c.Id == car.Category.Id).First();
car.CategoryReference.EntityKey = category.EntityKey;
context.UpdateCar(car);
context.SaveChanges();
return RedirectToAction("Index");
}