I have 2 similar queries:
ICmOption optionRes = CmOptionRepository<ICmOption>
.GetAll()
.Where(option => option.Name == strCommandName && option.Data == strCommandOption)
.FirstOrDefault()
;
IErrorType errorType = ErrorTypeRepository<IErrorType>
.GetAll()
.Where(et => et.ComponentId == (int)component.Id && et.ComponentErrorCode == strErrorCode)
.First()
;
In both cases constant data from DB are fetched. Due to this reason I want to cache results of these queries...
the simplest solution for one request is:
public IErrorType GetErrorType(IComponent component, string strErrorCode)
{
IErrorType errorType;
string strKey = string.Concat(component.Id, "_", strErrorCode);
lock (Dict)
{
if (Dict.ContainsKey(strKey))
{
errorType = Dict[strKey];
}
else
{
errorType = Repository
.GetAll()
.Where(et => et.ComponentId == (int)component.Id && et.ComponentErrorCode == strErrorCode)
.First()
;
Dict.Add(strKey, errorType);
}
}
return errorType;
}
private static Dictionary<string, IErrorType> Dict { get { return _dict; } }
private static readonly Dictionary<string, IErrorType> _dict
= new Dictionary<string, IErrorType>();
I do need the similar for the 2nd entity, and few more are coming... So I want to create a class (CachableRepository) that will accept parameters, check if object for them is cached already, if not - get data from DB and put to cache. And this should work for different number of parameters..
The problem is: I don't see a simple way how to create a key for cache for a different parameters, and how to build a lambda-function for these parameters...
If you have any thought or suggestion, please share them.
Thanks a lot!