I am working on an ASP.NET MVC project. The data access in through a repository that has a simple caching functionality. It contains several functions like the follwing two:
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
As you can see, they use the same workflow, over and over again. I want to remove this redundancy. I think that generics should provide a solution, but I can’t for the life of me figure out how to deal with the LINQ statements in a generic SelectAllEntities(Of T) function. Is there a way to ‘generalize’ the queries, maybe with dynamic LINQ?
My VB is a little rusty but I think you want to write your function like this.
Which you could use like this