我正在尝试将包含此Expression
的Linq-to-Entity运行到Entity Framework中。
不工作:
//2 seperated expressions, 1st expression calling the 2nd expression
public Expression<Func<User, UserDto>> UserToDtoExpr() {
var expr = AddressToDtoExpr();
return x => new UserDto() {
Id = x.Id,
Name = x.Name,
Address = expr.Compile()(x.Address)
};
}
public Expression<Func<Address, AddressDto>> AddressToDtoExpr() {
return x => New AddressDto() {
Id = x.Id,
City = x.City,
Country= x.Country
};
}
例外:The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
现在,我是硬编码并将其嵌套到一个Expression
中并将其放入Linq-to-Entity然后它可以工作:
//hardcode combined together into 1 expression with nested object
public static Expression<Func<User, UserDto>> UserToDtoExpr() {
return x => new UserDto() {
Id = x.Id,
Name = x.Name,
Address = New AddressDto() {
Id = x.Address.Id,
City= x.Address.City,
Country = x.Address.Country
}
};
}
但我不想像第二种方式那样硬编码,因为我想模块化并重用这些Expression
函数。如何修复第一种使其工作的方法?感谢。