Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I serialize a LINQ-to-SQL lazy list

I have a linq query and I am trying to put that in to a serializable object for a distributed caching (Velocity) but its failing due to a LINQ-to-SQL lazy list

like so

  return from b in _datacontext.MemberBlogs
                   let cats = GetBlogCategories(b.MemberBlogID)
                   select new MemberBlogs
                   {
                       MemberBlogID = b.MemberBlogID,
                       MemberID = b.MemberID,
                       BlogTitle = b.BlogTitle,
                       BlogURL = b.BlogURL,
                       BlogUsername = b.BlogUsername,
                       BlogPassword = b.BlogPassword,
                       Categories = new LazyList<MemberBlogCategories>(cats)
                   };

LazyList is the same class Rob Conery uses in his MVC storefront...

all three classes are marked serializable (MemberBlogs,MemberBlogCategories,LazyList... any ideas?

like image 308
dswatik Avatar asked Nov 05 '08 20:11

dswatik


2 Answers

If you are putting it in a distributed cache you will need to avoid the LazyList altogether. You can then call .ToList() around the whole LINQ statement as in:

(from x select new MemberBlogs).ToList()

This should then be cachable because it forces the queries to be evaluated.

like image 158
Duncan Avatar answered Sep 29 '22 10:09

Duncan


I'm just guessing, but I'd say the problem is that it is serializing the query instead of the results; I don't know what the implementation of the LazyList looks like, but you can probably add an OnSerializing method that actually executes the query prior to serializing it; Something like:

[OnSerializing]
private void ExecuteLinqQuery(StreamingContext context)
{
    if (!SomethingThatIndicatesThisLinqQueryHasNotBeenExecuted)
        LinqVariable.ToList()
}

This way you get to keep the Lazy Load (for anything that doesn't go into your cache), but then also if it does hit the cache, it'll execute the linq query and cache the results.

like image 37
Chris Shaffer Avatar answered Sep 29 '22 09:09

Chris Shaffer