0

ASP.NET MVC プロジェクトに取り組んでいます。単純なキャッシュ機能を持つリポジトリを介したデータ アクセス。次の 2 つのようないくつかの関数が含まれています。

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 に答える