Is it possible to serialize an Expression<T>
or LambdaExpression
? I need to save the expression tree in a database (varchar
column).
var expr = (LambdaExpression)expression;
if (expr != null)
{
var newBody = Expression.Convert(expr.Body, typeof(string));
var expr2 = Expression.Lambda(newBody, expr.Parameters);
var castedExpression = expr2 as Expression<Func<ShipmentViewModel, string>>;
Func = castedExpression.Compile();
}
I want to reconstruct the LambdaExpression
, compile and reuse it. Currently, I'm not able to find any solution.
Expressions are not serialisable. However, there are some third-part tools that may help.
I would recommend looking at Serialize.Linq. It is up to date, maintained, has a healthy number of downloads and will support .NET Framework 4.x as well as .NET Standard.
From the examples, it's pretty simple to use too:
Expression expression = Expression.Parameter(typeof(Person), "x");
// Serialize expression
var serializer = new ExpressionSerializer(new JsonSerializer());
string value = serializer.SerializeText(expression);
Console.WriteLine("value:" + value);
// Deserialize expression
var actualExpression = serializer.DeserializeText(value);
Console.WriteLine("actualExpression:" + actualExpression.ToJson());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With