0

我也在尝试更新实体及其相关实体。例如,我有一个带有属性 Category 的类 Car,我想更改它的 Category。所以,我在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 属性时,实体状态更改为已添加,而不是保持为已分离。

如何在不设置所有属性的情况下更新与 Entity Framework 和 ASP.NET MVC 的一对一关系,就像这篇文章一样?

4

1 回答 1

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");
}
于 2010-04-11T01:39:59.067 回答