Forum


HomeHomePremiumPremiumDevelopmentDevelopmentDAL 2 Caching with .Find()DAL 2 Caching with .Find()
Previous
 
Next
New Post
10/9/2013 10:15 AM
 

I am in a situation where my typical queries to the repository need to be run using the .Find() method.  This is somewhat unfortunate because using the Find() method requires the SQLCondition parameter that results in disabling automatic caching (http://www.charlesnurse.com/Blog/tabi...).  I added a couple lines of code to tackle this issue and thought I would share it here.

 The method is very simple and slightly modified from the DataAccess example provided by Scott:

public Item GetItemByName(string name)
{
    Item item = (Item)DataCache.GetCache(name);    //try to get the item from cache based on the parameters passed to the function
    if (item != null)
        return item;
    IList<Item> itemList;
    using (IDataContext ctx = DataContext.Instance())
    {
        var rep = ctx.GetRepository<Item>();
        itemList = (IList<Product>)rep.Find("WHERE name LIKE @0", name);
        if (itemList.Count > 0)
        {
            product = itemList[0];
            DataCache.SetCache(name, item); //if found, save the item to cache.
        }
    }
    return item;
}

In addition to adding the manual caching, I modified the function to return an Item rather than a IEnumerable.

This has tested well eliminating duplicate queries to the database.  It connects to the DNN caching so the Clear Cache tool can be used. 

I am guessing that the results from .Find() are not cached by default because there isn't a good way to invalidate the data during other CRUD operations since it is not connected to a Primary Key. 

One potential issue is that if other CRUD operations are used, it's possible to get an item represented in cache twice.  This would happen if a repository.GetById() and the GetItemByName() are used to locate the same product.  If you don't have a need for multiple R functions then this shouldn't be a problem.

If anyone has a better way of handling this let me know, otherwise put it in your toolbox.

 
Previous
 
Next
HomeHomePremiumPremiumDevelopmentDevelopmentDAL 2 Caching with .Find()DAL 2 Caching with .Find()



Try FREE
30 days money back guaranteed