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();
-
\$\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\$Snowbody– Snowbody2015年04月21日 13:53:37 +00:00Commented 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\$Pete– Pete2015年04月21日 14:01:08 +00:00Commented Apr 21, 2015 at 14:01
1 Answer 1
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.