0

我正在开发一个 ASP.NET MVC 项目。通过具有简单缓存功能的存储库访问数据。它包含几个功能,如以下两个:

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

如您所见,他们一遍又一遍地使用相同的工作流程。我想删除这种冗余。我认为泛型应该提供一个解决方案,但我一生都无法弄清楚如何处理泛型SelectAllEntities(Of T)函数中的 LINQ 语句。有没有办法“概括”查询,也许是动态 LINQ?

4

2 回答 2

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 的对象。我希望这将有所帮助。

于 2012-07-13T09:28:45.797 回答
1

我的 VB 有点生疏,但我想你想这样写你的函数。

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

你可以这样使用

Dim allCountries = SelectAll(db.Countries, Function(c) c.Title, "AllCountries")
于 2012-07-13T10:02:11.350 回答