转换表达式树
让它存在:
Expression<Func<Message, bool>> exp1 = x => x.mesID == 1;
Expression<Func<MessageDTO, bool>> exp2 = x => x.mesID == 1;
现在我需要将 exp1 传递给 _db.Messages.where(exp1);
问题是我只有 exp2,我需要将类型转换为 Message ,所有属性都是相同的!
现在我这样做:
var par = Expression.Parameter(typeof(Message));
var ex = (Expression<Func<Message, bool>>)Expression.Lambda(exp2.Body, par);
问题是输入参数被更改了是的!但 lambda“x.mesID”主体内的 x 是旧类型。
有什么方法可以更改正文中的所有参数类型或更改它也反映正文的输入参数吗?
我想这是我在使用 LINQ 时一直遇到的一个大问题,因为在层之间我无法传递生成的类,因为这将使层耦合,所以我必须创建轻量级类,现在我如何使用像 _db.Messages 这样的方法。在哪里();来自繁忙层?!!而业务层不知道任何有关消息类型的信息,它只知道 MessageDTO。
let there be :
Expression<Func<Message, bool>> exp1 = x => x.mesID == 1;
Expression<Func<MessageDTO, bool>> exp2 = x => x.mesID == 1;
now i need to pass exp1 to _db.Messages.where(exp1);
problem is i only have exp2, i need to convert the type to Message , All properties are the same !
now i do this :
var par = Expression.Parameter(typeof(Message));
var ex = (Expression<Func<Message, bool>>)Expression.Lambda(exp2.Body, par);
problem with this is the input paramter gets changed yes ! but the x inside the body of the lambda "x.mesID" is of the old type.
any way to change all the parameters type in the body too or change the input parameter in away it reflect the body too ?
i guess this is a big problem i always have with LINQ , since between layers i cant pass the generated classes , as this will make layers coupled , so i have to make light weight classes , now how do i use a method like _db.Messages.where(); from busiess layer ?!! while busniess layer doesnt know anything about Message type it only know MessageDTO.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,基本上。表达式树是不可变的,并且包含完整的成员元数据(即
mesID
是messageDTO.mesID
)。为此,您必须从头开始重建表达式树(通过访问者),处理您需要支持的每个节点类型。如果表达式树是基本,这应该没问题,但是如果您需要支持整个范围呢?一个巨大的 PITA(特别是在 .NET 4 中,它添加了更多的节点类型)。
一个基本示例,仅完成示例所需的内容;您需要为更复杂的表达式添加更多节点类型:
No, basically. Expression trees are immutable, and contain full member meta-data (i.e. that
mesID
ismessageDTO.mesID
). To do this, you would have to rebuild the expression tree from scratch (via a visitor), handling every node type you need to support.If the expression tree is basic this should be OK, but if you need to support the entire gamut? a huge PITA (especially in .NET 4, which adds a lot more node-types).
A basic example that does just what is required for the example; you would need to add more node-types for more complex expressions: