c# - 序列化 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
、编译和重用它。目前,我找不到任何解决方案。
解决方案
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());
推荐阅读
- r - 如何根据 RShiny 中的 LDAP 凭据对仪表板进行身份验证
- .net - SpecFlow 表中的原语列表
- ssl - SSL 证书:我们如何使网站对浏览器不安全
- php - 使用 Facebook PHP SDK Transformer 从图像中提取标题
- c++ - Unicode big endian 某些字符无法从 wchar_t 数组中正确获取
- r-markdown - 获取带有列单位的第二个标题
- java - JCEF - 访问浏览器窗口对象
- docker-compose - Haproxy 未绑定到 Ubuntu Server 18.04 上的前端
- php - $_FILES 变量中的部分数据
- django - 名称解析通道 2 django 中的临时故障