2010-04-10 5 views
0

엔티티와 관련 엔티티도 업데이트하려고합니다. 예를 들어, Category 클래스가있는 클래스 Car가 있고 그 카테고리를 변경하려고합니다.ASP.NET MVC를 사용하는 Entity Framework. 엔티티 문제 업데이트

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 후 범주 속성을 설정할 때 내 컨트롤러에서 엔터티 상태가 Detached로 남아있는 대신 Added로 변경됩니다.

this 게시와 같은 모든 속성을 하나씩 설정하지 않고 Entity Framework 및 ASP.NET MVC와 일대일 관계를 업데이트하려면 어떻게해야합니까?

+0

C => c.Id == 자동차 .Category.Id)'. –

답변

1

사람들, 방금 해결 방법을 알았습니다. Category 속성에서 전체 객체를 설정하는 대신 reference 속성에 엔터티 키만 설정해야합니다.

그래서, 이것은 잘못된 것입니다 :

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

그리고 이것은 올바른 방법입니다 : 당신은`context.Categories.First를 (쓸 수 여담으로

[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"); 
} 
관련 문제