2013-09-02 1 views
3

WebAPI를 사용하여 엔티티 프레임 워크에 대한 일반적인 구현을 작성하려고합니다. 나는 대부분의 메소드를 잘 구현할 수 있지만, 사소한 경우 PUT이 까다로울 수는 없다.자식 목록과 함께 작동하는 Entity Framework에 대한 일반 WebAPI Put 메서드를 작성하는 방법은 무엇입니까?

[HttpPut] 
    [ActionName("Endpoint")] 
    public virtual T Put(T entity) 
    { 
     var db = GetDbContext(); 
     var entry = db.Entry(entity); 
     entry.State = EntityState.Modified; 
     var set = db.Set<T>();    
     set.Attach(entity);      
     db.SaveChanges(); 
     return entity; 
    } 

을 ...하지만 자식 목록 삭제하거나 업데이트하지 않습니다 : 가장 일반적으로 온라인으로 볼 구현은 간단한 엔티티 작동하는 MVC 컨트롤러에서

public class Invoice 
    { 
     ... 
     public virtual InvoiceLineItem {get; set;} //Attach method doesn't address these 
    } 

을, 당신은 단순히 "UpdateModel"를 사용할 수 있으며, 필요에 따라 자식을 추가/업데이트/삭제하지만,이 메서드는 ApiController에서 사용할 수 없습니다. 일부 코드는 데이터베이스에서 원래 항목을 가져 오는 데 필요하며 Include를 사용하여 하위 목록을 가져와야하지만 UpdateModel의 기능을 복제하는 가장 좋은 방법을 알 수는 없다는 점을 알고 있습니다.

[HttpPut] 
    [ActionName("Endpoint")] 
    public virtual T Put(T entity) 
    { 
     var db = GetDbContext(); 
     var original = GetOriginalFor(entity); 
     //TODO: Something similar to UpdateModel(original), such as UpdateModel(original, entity);     
     db.SaveChanges(); 
     return original; 
    } 

어떻게 UpdateModel을 구현할 수 있습니까? 아니면 어떻게 든 자식 목록을 처리 할 수있는 방식으로 구현합니까?

답변

1

루틴은 엔티티의 유효성을 검사하지 않지만 이미 존재하는 엔티티를 채 웁니다.

protected virtual void UpdateModel<T>(T original, bool overrideForEmptyList = true) 
    { 
     var json = ControllerContext.Request.Content.ReadAsStringAsync().Result; 
     UpdateModel<T>(json, original, overrideForEmptyList); 
    } 

    private void UpdateModel<T>(string json, T original, bool overrideForEmptyList = true) 
    { 
     var newValues = JsonConvert.DeserializeObject<Pessoa>(json);    
     foreach (var property in original.GetType().GetProperties()) 
     { 
      var isEnumerable = property.PropertyType.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)); 

      if (isEnumerable && property.PropertyType != typeof(string)) 
      { 
       var propertyOriginalValue = property.GetValue(original, null); 
       if (propertyOriginalValue != null) 
       { 
        var propertyNewValue = property.GetValue(newValues, null); 

        if (propertyNewValue != null && (overrideForEmptyList || ((IEnumerable<object>)propertyNewValue).Any())) 
        { 
         property.SetValue(original, null); 
        } 
       } 
      } 
     } 

     JsonConvert.PopulateObject(json, original); 
    } 

    public void Post() 
    {   
     var sample = Pessoa.FindById(12); 
     UpdateModel(sample);    
    } 
관련 문제