O.O
O.O

Reputation: 11307

How to query cache instead of entity?

The Scenario:

  1. CustomerEntity represents the Customer table in the database.
  2. There are several queries that return CustomerEntities (list and single customer)

How is it possible to "fake" (proxy?) the CustomerEntity so that all queries attempt to hit the cached CustomerEntities. Obviously, in each query I can use the cache-aside pattern, for each individual query, but I want to use it for the entire Customer table regardless of the query.

(Cache-aside)

    private static readonly DataCache cache = CacheUtil.Instance.Cache;
    public List<Customer> GetCustomers()
    {
        string cacheKey = "test";
        var list = (List<Customer>)cache.Get(cacheKey);
        if (list == null)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var customers = context.Customer.Where(w => w.CustomerId > 10).ToList();

                list = new List<Customer>();
                foreach (var customer in customers)
                    list.Add(customer);
                cache.Put(cacheKey, list);
                return list;
            }
        }
        else
        {
            return list;
        }
    }

Upvotes: 1

Views: 356

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

That would require writting custom implementation of IObjectSet<T> which would either return data from cache or query the real internal ObjectSet<T>. Instances of this implementation will be exposed on your context instead of default ObjectSet<T>. Another and more simple approach is simply hiding your context and exposing queries only by specified method like GetQuery() - all your queries will use this method instead of context.Customer because context will be inaccessible for them.

You can also check Caching context wrapper.

Upvotes: 2

Related Questions