2012-07-13 3 views
0

ASP.NET MVC 프로젝트에서 작업 중입니다. 간단한 캐싱 기능을 가진 저장소를 통한 데이터 액세스. 다음과 같은 몇 가지 기능이 포함되어 있습니다.일반 함수의 LINQ 문

Public Function SelectAllCurrencies() As List(Of store_Currency) 
    Dim AllCurrencies As List(Of store_Currency) 
    If UseCaching Then 
     AllCurrencies = HttpContext.Current.Cache("AllCurrencies") 
     If AllCurrencies Is Nothing Then 
      AllCurrencies = (From Currencies In db.Currencies Order By Currencies.Title Ascending).ToList 
      Cache.AddToCache("AllCurrencies", AllCurrencies) 
     End If 
    Else 
     AllCurrencies = (From Currencies In db.Currencies Order By Currencies.Title Ascending).ToList 
    End If 
    Return AllCurrencies 
End Function 

Public Function SelectAllCountries() As List(Of store_Country) 
    Dim AllCountries As List(Of store_Country) 
    If UseCaching Then 
     AllCountries = HttpContext.Current.Cache("AllCountries") 
     If AllCountries Is Nothing Then 
      AllCountries = (From Countries In db.Countries Order By Countries.Title Ascending).ToList 
      Cache.AddToCache("AllCountries", AllCountries) 
     End If 
    Else 
     AllCountries = (From Countries In db.Countries Order By Countries.Title Ascending).ToList 
    End If 
    Return AllCountries 
End Function 

위에서 볼 수 있듯이, 이들은 동일한 워크 플로를 반복해서 사용합니다. 이 중복성을 제거하고 싶습니다. 제네릭은 솔루션을 제공해야한다고 생각하지만 제 인생에서 LINQ 문을 처리하는 방법을 일반 SelectAllEntities(Of T) 함수로 파악할 수는 없습니다. 동적 LINQ를 사용하여 쿼리를 '일반화'할 수 있습니까?

+0

처럼 사용할 수

Public SelectAll(Of T, TOrder)( IEnumerable(Of T) source, Func(Of T, TOrder) keySelector, cacheKey As String = Nothing) As IList(Of T) Dim all As List(Of T) If me.UseCaching Then all = HttpContext.Current.Cache(cacheKey) If all Is Nothing Then all = source.OrderBy(keySelector).ToList() Cache.AddToCache(cacheKey, all) End If Else all = source.OrderBy(keySelector).ToList() End If Return all End Function 

는'(T의) 유형 '을 IEnumerable없이 단지 매개 변수인가? – Jodrell

답변

1

VB는 약간 녹슬었지만 이런 식으로 함수를 작성하려고합니다. 이

Dim allCountries = SelectAll(db.Countries, Function(c) c.Title, "AllCountries") 
+0

고마워, 잘 생겼어! @ethicallogics의 답변과 함께 우리 코드 기반에 가장 적합한 방법을 찾아 낼 수 있어야합니다. 나는 내 솔루션이 어떻게 받아 들여지는지 알기 위해 어떻게 대답해야만 할까 ;-) 참고 : VB 구문은 내 눈을 아프게한다. – Treb

2
 public List<T> GenericMethod<T>(string str) 
    { 
     List<T> list; 
     list=HttpContext.Current.Cache(str); 
     if(list==null) 
     { 
      using(var db=new ObjectContext()) 
      { 
       list=db.CreateObjectSet<T>().ToList(); 
      } 
     } 
     return list; 
    } 
    public void GetCountries() 
    { 
     var countries = GenericMethod<AllCountries>("AllCountries").OrderBy(o => o.Title).ToList(); 
    } 

    public void GetCurrencies() 
    { 
     var currencies = GenericMethod<AllCurrencies>("AllCurrencies").OrderBy(o => o.Title).ToList(); 
    } 

및 db는 ObjectContext의 개체입니다. 이것이 도움이되기를 바랍니다.

+0

아, 고맙습니다. 이것이 최종 답변인지 확실하지 않지만, 확실히 나에게 출발점을 제공합니다! – Treb