我正在开发一个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?
答案 0 :(得分: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的对象。我希望这会有所帮助。
答案 1 :(得分: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")