2
\$\begingroup\$

I was just getting some products using entity framework and was wondering which would be better to do when getting the results, or if there is no difference.

Option 1 - Query the context directly

return dbContext
 .PPCProducts
 .Include(p => p.Attributes)
 .Include(p => p.ChildProducts)
 .Where(p => p.Attributes.FirstOrDefault(a => a.AttributeName.IndexOf(attributeName, StringComparison.InvariantCultureIgnoreCase) > -1) != null)
 .OrderBy(p => p.ProductName)
 .ToList();

Option 2 - Query the cache

// cache the products
var products = dbContext
 .PPCProducts
 .Include(p => p.Attributes)
 .Include(p => p.ChildProducts);
CacheHelper.Add("products", products, CacheDuration.Hours3);
// query the cache
return ((List<Product>)HttpContext.Current.Cache["products"]).Where(p => p.Attributes.FirstOrDefault(a => a.AttributeName.IndexOf(attributeName, StringComparison.InvariantCultureIgnoreCase) > -1) != null)
 .OrderBy(p => p.ProductName)
 .ToList();
asked Apr 21, 2015 at 13:24
\$\endgroup\$
2
  • \$\begingroup\$ If your database server is configured anywhere close to correctly, there should be no difference. So I'd lean towards the simpler code. \$\endgroup\$ Commented Apr 21, 2015 at 13:53
  • \$\begingroup\$ Ah ok, thanks - although I have found I can't do the index of on the db so I need to change that sub query \$\endgroup\$ Commented Apr 21, 2015 at 14:01

1 Answer 1

2
\$\begingroup\$

There are a few potential issues here, speed and accuracy in particular.

Speed

The cache is often faster than querying a value directly because of computation - you need to input, process, calculate, and output values. For example, when you search the web, the servers return results based on cached data so they don't have to literally scan every website, read keywords, process data, etc. Reading from the cache is as simple as getting the final value with no computation involved.

Accuracy

Querying a cache can return obsolete data. Let's say you have a product priced at $X, and change the price for a sale. If you don't update the cache, you will return outdated prices to your customers. Querying the original data bypasses the intermediate value, always ensuring the value is correct.

answered Jun 27, 2015 at 0:29
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.