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 函数。如何修复第一种方法以使其工作?谢谢。

您需要使用 LinqKitAsExpandable() 来实现。

首先,将表达式更改为使用 LinqKit 的 Invoke()(扩展方法),如下所示:

Address = expr.Invoke(x.Address) // instead of expr.Compile()(x.Address)

然后在你的 DbSet<T> 上使用 AsExpandable():

var results = context.Users.AsExpandable().Select(UserToDtoExpr());

阅读 this 以了解嵌套表达式的问题。