Cache individual object in asp.net mvc
Upon writing a controller for exporting image on the fly, I struggled with the problem that: "Output cache does not cache HttpHeader (in this case, "Location" header)". Which lead me to despair since each time i called the controller to output image, it will have to connect to database and do a couple of query, which is not practical in real life. So finally, i found out that i can easily cache objects into a cache provider in Asp.net Mvc. Very useful, all my queries go back to 0 (traced through Ling2sql profiler).
You can use this piece of code in anywhere of your code where you want to cache any object.
(Notice: this code was used in a controller, so I used HttpContext.Cache. But if you use else where that make this code not working, try HttpContext.Current.Cache)
1 2 3 4 5 6 7 8 9 10 | if (HttpContext.Cache["ObjName"] != null) { link = (string)HttpContext.Cache["ObjName"]; return link; } else { HttpContext.Cache.Add("ObjName", link, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(30, 0, 0, 0, 0), System.Web.Caching.CacheItemPriority.High, null); return link; } |
What it did was to check if the ObjName exist in the context, if not, create one and dump the data into it. Remember when you call back from HttpContext, it's an object so you always need a cast. If you don't know about argument, let the intellisense do the work for you.
Time to exand further about the topic: HttpContext.Cache.Add
Query a set of IDs from SQL using LINQ to SQL
Just not so long ago, I have a hard time while doing this in LINQ to SQL since i have my datacontext running on LINQ to SQL. I was force to do a N+1 querry, which is extremely expensive on both CPU and Time since i put my SQL Server else where that not in local and each query cost me 200ms in time.
My N+1 query was look like this:
SELECT * FROM Image WHERE IMG_ID = 1 SELECT * FROM Image WHERE IMG_ID = 3 SELECT * FROM Image WHERE IMG_ID = 7 SELECT * FROM Image WHERE IMG_ID = 9
however, later i found out a way to solve this by using "Contains" from IList to query "WHERE IN(x,x,x)".
Here is one function in my Repository:
1 2 3 4 5 6 | public List<Image> Images(IList<int> idList) { return (from d in _db.Images .Where<Image>(d => idList.Contains<int>(d.IMG_ID)) select d).ToList<Image>(); } |
or better:
1 | return _db.Images.Where<Image>(x => idList.Contains<int>(x.IMG_ID)).ToList<Image>(); |
these will output:
SELECT * FROM Image WHERE IMG_ID IN(1,3,7,9)