首页 > 解决方案 > 序列化 LambdaExpression 到字符串和从字符串中保存以保存在数据库中

问题描述

是否可以序列化Expression<T>or LambdaExpression?我需要将表达式树保存在数据库(varchar列)中。

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();
}

我想重建LambdaExpression、编译和重用它。目前,我找不到任何解决方案。

标签: c#linqserializationexpression

解决方案


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());

推荐阅读