엔티티와 관련 엔티티도 업데이트하려고합니다. 예를 들어, 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와 일대일 관계를 업데이트하려면 어떻게해야합니까?
C => c.Id == 자동차 .Category.Id)'. –