This project is read-only.

SerializableExpression back to Expression

Jun 28, 2009 at 11:09 PM

What would be the easiest way to return SerializableExpression back to the normal LINQ Expression ?

I don't want to exec my SerializableExpression (which i sent as a param to the server via my custom code...), i need to return it to normal LINQ Expression in order to do some additional work before i execute it...

Jul 1, 2009 at 2:54 PM
Edited Jul 1, 2009 at 3:07 PM

Hi SubGate

That's a good question. The abstract Class InterLinq.Expressions.Helpers.SerializableExpressionVisitor has a Visit Method which takes a SerializableExpression and returns a converted Expression. But it can't be useed directly because it's not static. If you want to use it, you will have to work with the SerializableExpressionConverter, the implementation of the abstract class. You have to create it with a SerializableExpression and an IQueryHandler witch you won't need anymore afterwards:

SerializableExpression e = new SerializableConstantExpression();
IQueryHandler h = new ClientQueryHandler();
SerializableExpressionVisitor visitor = new SerializableExpressionConverter(e, h);

Then you have to take your SerializableExpression and convert it with the Visitor (in this example it is a simple constant expression)

SerializableExpression toConvert = new SerializableConstantExpression(Expression.Constant("test"), null);
Expression converted = visitor.Visit(toConvert);

After that you have your converted Expression. The creation of the Visitor is a bit dirty though, because InterLinq is designed to convert the SerializableExpression into an Expression and then directly to return the results. Perhaps I can find a way to seperate those two steps so you can use one of them seperately, but until then this should work also.

Kind regards


Feb 21, 2011 at 3:24 AM

Thanks, Winston.  I was wondering this also.

Here is the completed code for serializing & deserializing an Expression Tree using InterLINQ.

        public void TestSerialization()
            Expression<Func<Guid, bool>> expression = (guid) => guid != Guid.Empty;


        private static void AssertSerialization(Expression expression)
            var serialized = Serialize(expression);
            var deserialized = Deserialize(serialized);

            Assert.AreEqual(expression.ToString(), deserialized.ToString());

        private static SerializableExpression Serialize(Expression expression)
            return expression.MakeSerializable();

        private static Expression Deserialize(SerializableExpression serialized)
            // Create Visitor
            SerializableExpression fakeExpression = new SerializableConstantExpression();
            IQueryHandler fakeHandler = new ClientQueryHandler();
            SerializableExpressionVisitor visitor = new SerializableExpressionConverter(fakeExpression, fakeHandler);

            return visitor.Visit(serialized);