tags:

views:

77

answers:

4

I have a request for a feature to be able to save a user's search for later.

Right now I'm building LINQ statements on the fly based on what the user has specified.

So I started wondering, is there an easy way for me to simply take the query that the user built, and persist it somewhere, preferably my database, so that I can retrieve it later?

Is there some way of persisting the query as XML or perhaps JSON, and then reconstituting the query later?

A: 

Take a look at the Expression class. This will allow you to pre-compile a query. Although persisting this for later use to the DB for better performance is questionable.

Daz Lewis
@Daz something like System.Data.Linq.CompiledQuery or were you referring to something else?
Joseph
+2  A: 

Never done this before, but I've had this idea:

Rather than having the query run against your database directly, if you were to have it run against an OData endpoint, you could conceivably extract the URL that is generated as the query string, and save that URL for later use. Since OData has a well-though-out spec already, you would be able to profit from other people's labor.

StriplingWarrior
That's not a half bad idea. So then I would need to build an OData endpoint on my server, and just consume that on my website for saved queries? Is that the idea?
Joseph
Yeah, that's the idea. The neat thing is that the endpoint would be as public as you want it to be, and you could restrict it to include only a subset of your model. The same way that we can connect to StackOverflow with LinqPad to discover interesting metrics, you could enable certain clients or business analysts to have a flexible, queryable view into your data. Also, by creating the extra layer, even if your underlying model changes, you can make sure that the OData endpoint's model stays the same.
StriplingWarrior
+3  A: 

I'd go with a domain-specific object here even if such goodies did exist -- what happens when you save serialized queries in LINQ and your underlying model changes, invalidating everyone's saved queries. Using your own data format should shield you from this to some extent.

Wyatt Barnett
@Wyatt I'm not really worried about my underlying model changing. I'm not saying that's not a valid concern, but in my case I don't have to worry about my model changing.
Joseph
Not talking about your model, but rather the (perhaps non-existent anyhow) facilities for serializing queries. I'd bet whatever lives there will change with internals as the Framework evolves.
Wyatt Barnett
A: 

I'm writing this as I watch this presentation at PDC10. Just after the 1-hour mark, he shows how he's built a JSON serializer for expression trees. You might find that interesting.

StriplingWarrior