I got simple LINQ expression trees to serialize last night. As I expected, the direct approach is to create a parallel set of expression types for each type in System.Linq.Expressions. With a set of serializable expression types, serialization is a snap. Here's what the code needs to do:
For Serialization
- Perform partial evaluation on the LINQ expression tree. See this article by Matt Warren for code that supports partial evaluation. See my previous post for why this step is necessary.
- Map each LINQ expression to a corresponding serializable expression. A visitor class greatly simplifies this step.
- Serialize the expression tree. I tested with the BinaryFormatter, but I'm confident the DataContractSerializer would work as well with its support for [Serializable] types.
For De-serialization
- De-serialize the expression tree.
- Map each serializable expression back to its original LINQ expression. Again, a visitor class is recommended for this step.
- Use the expression tree.
As of now, my code supports lambda, parameter, constant, methodcall, and a convert expressions. To support the rest, it should be just a matter of implementing the remaining expression types as the proof of concept worked.
Comments