Reputation: 9645
I'm using a LinqToSql query to select a list of groups from a database and spew out a table. I've written a custom class to cache the results of this query for better performance. Trouble is, whenever I implement the caching class, I get weird appending behaviour from the outputting statement.
My results are outputted in the format
Test Group (1)
where "Test Group" is the name, and (1) is the number of members within that group. Here's the code that appends the count to the name (from the view)
<td>@group.group_name (@group.num_total)</td>
When I pull this from a live linq query returning groups, everything works as expected.
However, when I use my caching class, every successive page load adds the number on to the end of the group title:
Test Group (1) (1) (1) (1) (1) (1)
This only happens when I use the caching class (included below). I've been over the cache class and there's no reason I can see why this would be happening.
I can think of several workarounds for this issue, so its not a show stopper, but I'm curious as to what the fudge is going on. Any ideas?
Caching Class:
public class Cache
{
public static int user_id {
get { return
Convert.ToInt32(
Membership.GetUser(
HttpContext.Current.User.Identity.Name
).ProviderUserKey
);
}
}
public static void GetGroups_InvalidateCache()
{
if (HttpContext.Current.Cache["GetGroups_" + user_id] != null)
HttpContext.Current.Cache.Remove("GetGroups_" + user_id);
}
public static ICollection<Groups> GetGroups()
{
if (HttpContext.Current.Cache["GetGroups_" + user_id] == null)
{
using(DBContext db = new DBContext())
{
var Groups = (from g in db.Groups
where g.user_id == user_id
select g).ToList();
HttpContext.Current.Cache.Insert(
"GetGroups_" + user_id,
Groups,
null,
DateTime.Now.AddMinutes(5),
TimeSpan.Zero
);
}
}
return HttpContext.Current.Cache["GetGroups_" + user_id]
as ICollection<Groups>;
}
}
UPDATE:
I've now implemented Adam Tuliper and Paul Tyng's suggestions of calling the data context with the using
clause, ending the linq statement with ToList()
and using ICollection
instead of IQueryable
. The problem is still occurring.
Another interesting observation: The issue only happens if I navigate away to another page and return. If I simply refresh the page, it doesn't happen (Although any previous number additions still remain when I refresh)
Upvotes: 2
Views: 545
Reputation: 30152
Instead of returning IQueryable, try using simply IEnumerable and also using
using(DBContext db = new DBContext()) { var Groups = (from g in db.Groups where g.user_id == user_id select g).ToList(); ... }
Also dispose of your context as in the above statement (with the using clause)
The ToList() forces the execution "now" - I think you are potentially having deferred execution issues
Upvotes: 2