如何在Entity Framework中定义表达式选择嵌套的一对一关系

时间:2015-04-30 06:39:55

标签: c# entity-framework linq-to-entities

我正在尝试将包含此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函数。如何修复第一种使其工作的方法?感谢。

0 个答案:

没有答案