Entity Framework 如何定义表达式选择嵌套的一对一关系
How to define expression selection nested one-to-one relationship in Entity Framework
我正在尝试 运行 包含此 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
函数。如何修复第一种方法以使其工作?谢谢。
我正在尝试 运行 包含此 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
函数。如何修复第一种方法以使其工作?谢谢。