Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize LambdaExpression to and from string for saving in a database

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.

like image 830
BendEg Avatar asked Oct 21 '25 15:10

BendEg


1 Answers

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());
like image 186
DavidG Avatar answered Oct 23 '25 03:10

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!