Entity Framework с ASP.NET MVC. Проблема с обновлением объекта

Я пытаюсь обновить объект и связанные с ним объекты. Например, у меня есть класс Car со свойством Category, и я хочу изменить его категорию. Итак, у меня есть следующие методы в контроллере:

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");
    }

Метод UpdateCar в классе ObjectContext выглядит следующим образом:

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 в моем контроллере, состояние объекта изменяется на «Добавлено», а не остается «Отсоединенным».

Как я могу обновить отношение один к одному с Entity Framework и ASP.NET MVC, не устанавливая все свойства по одному, например этот пост?


person Kitaly    schedule 10.04.2010    source источник
comment
Кроме того, вы можете написать context.Categories.First(c => c.Id == car.Category.Id).   -  person Marcelo Cantos    schedule 11.04.2010


Ответы (1)


Хорошо, люди, я только что узнал, как это можно решить. Вместо установки всего объекта в свойстве «Категория» необходимо установить только ключ объекта в свойстве ссылки.

Итак, это неправильно:

[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");
}
person Kitaly    schedule 11.04.2010