2012-06-21 5 views
1

멀티 사이트 웹 사이트를 다루는 데 도움이되는 모델 바인더가 있습니다. 각 StoreObject에는 SiteThemes 컬렉션이 있습니다.모델 바인더에서 엔티티가 업데이트되지 않음

public class StoreObject 
{ 
    ....... 
    public virtual ICollection<SiteTheme> SiteThemes { get; set; } 
} 

I는 새로운 테마로 데이터베이스를 업데이트하는 저장소 객체를 호출합니다. 그이 완료되면

public void SaveAndSetSiteTheme(SiteTheme t) 
{ 
    context.SiteThemes.Where(f => f.StoreObjectID == t.StoreObjectID).ToList().ForEach(p => p.Active = false); 
    if (t.SiteThemeID == 0) 
    { 
      t.Active = true; 
      context.SiteThemes.Add(t); 
    } 
    context.SaveChanges(); 

} 

, 모델 바인더는 아래의 정확한 데이터를 가지고 store.SiteThemes은 1 개 테마를해야합니다. 그러나이 페이지를 다시 새로 고치면이 모델 바인더가 오래되었습니다. store.SiteThemes 콜렉션은 원래 상태로 돌아가며 비어 있습니다. 나는 지구상에서 무슨 일이 벌어지고 있는지 전혀 모른다. 자세한 정보가 필요하면 알려주십시오.

public class StoreModelBinder : IModelBinder 
{ 
    private const string sessionKey = "Store"; 

    private IStoreObjectRepository storeRepository; 

    public StoreModelBinder() 
    { 
     storeRepository = new StoreObjectRepository(); 
    } 

    public object BindModel(ControllerContext controllerContext, 
     ModelBindingContext bindingContext) 
    { 

     Uri url = HttpContext.Current.Request.Url; 
     string dom = url.Host; 
     StoreObject store = storeRepository.Stores.FirstOrDefault(s => s.MainURL == dom); 
     if (store != null) 
      HttpContext.Current.Session[sessionKey] = store; 

     return store; 
    } 
} 
+0

어디에서 컨텍스트를 인스턴스화합니까? 또한 연결 문자열을 확인하십시오. 일반적으로이 문제가 발생하면 데이터베이스에 연결하고 있지 않기 때문에 오류가 발생하지 않습니다. 그냥 따라 실행하고 레코드가 생성/업데이트되지 않습니다. – Brian

답변

2

이 문제를 해결할 수있었습니다. 하지만, 이상적인 솔루션은 아닙니다.

"ModelBinders는 여러 요청에 대해 MVC에서 다시 사용되므로 요청 범위보다 긴 수명주기를 가지므로 요청 범위 수명주기가 짧은 개체에 의존 할 수 없습니다."

자료 : Inject a dependency into a custom model binder and using InRequestScope using Ninject

는 단순히 생명주기 문제 과거를 얻을 내 BindModel 내 StoreObjectRepository의 새로운 인스턴스를 추가했다. 나는 이것을 해킹으로보고 가까운 장래에이 코드를 업데이트 할 것이다.

public class StoreModelBinder : IModelBinder 
{ 
    private const string sessionKey = "Store"; 

    private IStoreObjectRepository storeRepository; 

    public StoreModelBinder() 
    { 
     storeRepository = new StoreObjectRepository(); 
    } 

    public object BindModel(ControllerContext controllerContext, 
     ModelBindingContext bindingContext) 
    { 
     storeRepository = new StoreObjectRepository(); 

     Uri url = HttpContext.Current.Request.Url; 
     string dom = url.Host; 
     StoreObject store = storeRepository.Stores.FirstOrDefault(s => s.MainURL == dom); 
     if (store != null) 
      HttpContext.Current.Session[sessionKey] = store; 

     return store; 
    } 
} 
관련 문제