问题描述
我有一个4层体系结构的项目,即UserInterface,BusinessLogic,Service(WCF)和DataAccess(EF6)层.我在服务上公开了接受表达式的方法,这些表达式可以传递给我的数据访问层以使用EF进行评估.但是,这不起作用,因为表达式不可序列化.
I have a 4 layered architectured project, i.e. UserInterface, BusinessLogic, Service(WCF) and DataAccess(EF6) layers. I have exposed methods on my service that accept an expression which I can pass to my dataaccess layer to be evaluated using EF. However, this does not work because the Expression is not serializable.
在客户端,我希望能够构建可查询的表达式以发送到服务器端并返回正确的投影.
On my client end I want to be able to build queryable expressions to send to the server side and return the correct projection.
服务器端:
public virtual IEnumerable<Person> Get(Expression<Func<Person, bool>> expression)
{
using (var ctx = MyContext())
{
IQueryable<PersonDto> col = ctx.DbContext.People.Where(expression);
//
return col.ToList();
}
}
客户端:
public IEnumberable<PersonDto> GetFromService(Expression<Func<PersonDto, bool>> expression)
{
using (MyService client = new MyService())
{
return client.Get(expression);
}
}
我执行此操作的方式是否有替代方法?表达式和函数无法序列化是有原因的吗?
Is there an alternative to the way I'm doing this? And is there a reason why expressions and funcs are not serializable?
推荐答案
您可以使用 Remote.Linq .该项目目前托管在GitHub上,但似乎没有任何文档.但是您可以使用CodePlex中的旧版本.
You can use Remote.Linq for this. The Project is currently hosted on GitHub, but it seems that there is no documentation. But you can use the old one from CodePlex.
最简单的方法(从旧文档中复制代码)
The easiest way to achieve this (Code copied from the old documentation)
// create linq expression
System.Linq.Expressions.Expression<Func<Order, bool>> linqExpression =
order => order.Items.Where(i => i.ProductId == prodId).Sum(i => i.Quantity) > 1;
// transform linq expression into serializable expression tree
Remote.Linq.Expressions.LambdaExpression serializableExpression =
linqExpression.ToRemoteLinqExpression();
// transform serializable expression tree back into linq expression
System.Linq.Expressions.Expression<Func<Order, bool>> recreatedLinqExpression =
serializableExpression.ToLinqExpression<Order, bool>();
这篇关于由于表达式树不可序列化,因此如何使用不能使用WCF的表达式树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!