Mike Taulty's Blog
Bits and Bytes from Microsoft UK
TechEd Europe - Follow Up 2. Serializing Expressions.

Blogs

Mike Taulty's Blog

Elsewhere

I met a couple of people at TechEd Europe who wanted to do something along the lines of;

Have a client which formulates a LINQ (to relational) query, serializes this LINQ query over the network to a remote middle-tier server and then that server executes the query before serializing the result-sets back to the client.

To be honest, I'm not sure that I understand the scenario where I'd want to do this because I kind of view applications as;

  1. Two tier. That is, use DataContext/ObjectContext in the application to formulate a LINQ (to relational) query and execute it against the database.
  2. N-tier. That is, the client does not see/use DataContext/ObjectContext and therefore can't formulate a LINQ (to relational) query and execute it against the database. It communicates with some service that does this for it.

If we were to try and pursue (2) then we'd need to have the client reference DataContext/ObjectContext when it wasn't actually going to use those local contexts to execute queries. It is using the local context purely to generate queries which it is then going to try and serialize. The client would also have to reference the (perhaps generated) entity data types that we're using (e.g. Customer, Order etc).

We'd then have to have the client serialize an expression that it'd built locally to send it to a server. Something perhaps like;

    static void Main(string[] args)
    {
      using (NorthwindDataContext ctx = new NorthwindDataContext())
      {
        var query = from c in ctx.Customers
                    where c.Country == "Spain"
                    select c;
      }
    }

If we wanted to serialize this then we'd need to grab query.Expression and serialize it which (AFAIK) would involve trying to serialize MethodCallExpression and (AFAIK) that isn't going to work. Additionally, if this query made reference to local objects/state then serializing those would be "a challenge" too.

So, AFAIK, you can't do this and my approach to generating an "unplanned" query on the client and sending it to the server would be to use some kind of string-based mechanism rather than trying to use an actual LINQ query for this. Both LINQ to SQL and LINQ to Entities will allow you to execute a string-based query and get back an object-based result-set and that's the way I'd go if I needed this kind of functionality.


Posted Sat, Nov 10 2007 5:46 AM by mtaulty

Comments

Jason Haley wrote Interesting Finds: November 10, 2007
on Sat, Nov 10 2007 8:55 AM
TechEd Europe - Follow Up 2. Serializing Expressions. wrote TechEd Europe - Follow Up 2. Serializing Expressions.
on Mon, Nov 26 2007 1:17 PM