I want to cache my entities to avoid database interactions where possible. When I do something like:
public IList<Website> Get()
{
//The `_cacheManager.Get` just retrieves the object from an `ObjectCache` instance based on key.
return _cacheManager.Get(CcCacheWebsiteAll, () => _websiteRepository.Table.ToList());
}
I am running into issues when retrieving a value from the cache and assigning it to a new object that requires an instance of that type.
For instance:
var store = new Store();
store.Name = "something";
store.Website = _websiteService.Get().FirstOrDefault();
_storeService.Insert(store);
//Where _storeService.Insert(store) is:
public void InsertStore(Store store)
{
_storeRepository.Insert(store); //THIS will raise the error
}
I would have thought that calling ToList()
on the Get()
method would throw the instances into a new list and stop the issue but I'm not finding this when testing.
Does anyone have any suggestions?
Note: Just to make sure I only have one context, I disabled caching and everything is working as expected.
Edit
Store Service Ctor:
public StoreService(IRepository<Store> storeRepository)
{
_storeRepository = storeRepository;
}
Website Service Ctor:
public WebsiteService(IRepository<Website> websiteRepository)
{
_websiteRepository= websiteRepository;
}