2013-10-07 1 views
0

여러 테이블의 데이터를 참조하는 ViewModel 쌍이 있습니다. 하나는 표시 용이고 다른 하나는 편집 용입니다.MVC에서 여러 테이블 업데이트 리포지토리를 사용하여 액션 편집

DisplayModel에서 데이터를 반환하면 ValueInjecter InjectFrom 기능을 사용하여 모든 관련 필드를 매핑 할 수 있습니다.

데이터베이스를 업데이트하려면 어떻게해야합니까?

모델을 리포지토리의 업데이트 방법으로 보내면 모델의 변경 사항을 볼 수 있지만 컨텍스트는이를 선택하지 않습니다. 제가 한 걸음도 놓치고 있습니까? 아니면 이것을하는 더 좋은 방법이 있습니까?

내가 한 번에 하나 개의 테이블을 수정하려고하면 나는 변경 사항을하지만 다음과 같은 오류를 얻을 수있는 컨텍스트를 얻을 수 있습니다 : 예기치 않은 에 영향을

스토어 업데이트, 삽입, 또는 문을 삭제 행 수 (0).

--- 편집 ---

나는 코드를 업데이트하고 저장소에 매핑을 이동하지만 여전히 디버거가 새로운 값으로 개체를 보여줍니다에도 같은 오류가 받고 있어요했습니다 .


ViewModels

public partial class HouseholdEditViewModel //for displaying in browser 
{ 
    public int entityID { get; set; } 
    public int familyID { get; set; } 
    public string UPRN { get; set; } 
    public string address { get; set; } 
    public HousingTypeDropDownViewModel housingTypeID { get; set; } 
    public KeyworkerDropDownViewModel keyworkerID { get; set; } 
    public string startDate { get; set; } 
    public bool loneParent { get; set; } 
    public string familyPhoneCode { get; set; } 
    public string familyPhone { get; set; } 
} 

public partial class HouseholdAddViewModel //for mapping to database 
{ 
    public int familyID { get; set; } 
    public string UPRN { get; set; } 
    public string address { get; set; } 
    public int entityTypeID { get; set; } 
    public int housingTypeID { get; set; } 
    public int keyworkerID { get; set; } 
    public DateTime startDate { get; set; } 
    public bool loneParent { get; set; } 
    public string familyPhoneCode { get; set; } 
    public string familyPhone { get; set; } 
} 

저장소는 (현재 버전 - 내가 성공하지 않고 몇 가지 다른 일을 시도했습니다)

public interface IHouseholdRepository : IDisposable 
{ 
    //other methods here... 

    void Update(HouseholdAddViewModel model, int id); 
} 


public void Update(HouseholdAddViewModel model, int id) 
{ 
    //check address exists 
    var address = (from u in context.tAddress 
        where model.UPRN.Contains(u.UPRN) 
        select u.UPRN); 

    var ae = new tAddressEntity(); 
    ae.InjectFrom(model); 
    ae.entityID = id; 
    ae.UPRN = model.UPRN; 

    context.tAddressEntity.Attach(ae); 
    context.Entry(ae).State = EntityState.Modified; 

    var e = new tEntity(); 
    e.InjectFrom(model); 
    e.entityID = id; 
    e.entityName = model.address; 
    e.tAddressEntity.Add(ae); 

    context.tEntity.Attach(e); 
    context.Entry(e).State = EntityState.Modified; 

    var a = new tAddress(); 
    a.InjectFrom(model); 

    context.tAddress.Attach(a); 
    context.Entry(a).State = address.ToString() == string.Empty ? 
          EntityState.Added : 
          EntityState.Modified;      

    var hs = new tHousingStatus(); 
    hs.InjectFrom(model); 
    hs.entityID = id;    

    context.tHousingStatus.Attach(hs); 
    context.Entry(hs).State = EntityState.Modified; 

    var k = new tKeyWorker(); 
    k.InjectFrom(model); 
    k.entityID = id; 

    context.tKeyWorker.Attach(k); 
    context.Entry(k).State = EntityState.Modified; 

    var l = new tLoneParent(); 
    l.InjectFrom(model); 
    l.entityID = id; 

    context.tLoneParent.Attach(l); 
    context.Entry(l).State = EntityState.Modified; 

    var h = new tHousehold(); 
    h.InjectFrom(model); 
    h.entityID = id; 
    h.tHousingStatus.Add(hs); 
    h.tKeyWorker.Add(k); 
    h.tLoneParent.Add(l);  

    context.Entry(h).State = EntityState.Modified; 

    context.SaveChanges(); 
} 

컨트롤러

[HttpPost] 
public ActionResult Edit(HouseholdAddViewModel model, int id) 
{   
    model.entityTypeID = _repo.GetEntityType(); 

    if (ModelState.IsValid) 
    { 
     _repo.Update(model, id); 
     return RedirectToAction("Index"); 

    } 
    return View("Edit", id); 
} 

답변

1

EF를 사용하여 엔티티를 업데이트하는 가장 쉬운 방법은 키를 사용하여 엔티티를 검색 한 다음 해당 개체 인스턴스에 업데이트를 적용하는 것입니다. EF는 엔티티에 대한 업데이트를 자동으로 감지하여 SaveChanges()에 전화 할 때 적용합니다.

새로운 엔티티를 생성하는 중이며 컨텍스트에 추가하지 않으므로 이 선택되지 않은 것처럼 보입니다.

나는이

[HttpPost] 
public ActionResult Edit(HouseholdAddViewModel model, int id) 
{ 
    model.entityTypeID = _repo.GetEntityType(); 

    if (ModelState.IsValid) 
    { 
     var h = _repo.GetHousehold(id); 
     h.InjectFrom(model); 
     h.entityID = id;  
     //... 
    } 
} 
+0

어떻게 다음 다른 모델 위에 속성을 매핑 할 할 당신의 편집 컨트롤러를 변경할 것인가? 올바른 속성을 볼 수는 있지만 관계형 방식으로 테이블을 업데이트 할 수는 없습니다. 예 : 엔티티 이름이 tEntity에서 업데이트되지만 AddressEntity가 변경 사항을 선택하지 않습니다 ... – melkisadek