How to define expression selection nested one-to-one relationship in Entity Framework

孤街醉人 提交于 2019-12-12 10:17:41

问题


I am trying to run a Linq-to-Entity that contains this Expression into Entity Framework.

Not Working:

//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
    };
}

Exception: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

Now, I if hardcode and nest it into one Expression and put it into Linq-to-Entity then it works:

//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
        }
    };  
}

But I don't want to hardcode it like the 2nd way, because I want to modularise and reuse these Expression functions. How do I fix up the 1st way to make it work? Thanks.


回答1:


You need to use LinqKit's AsExpandable() to achieve this.

First, change your expression to use LinqKit's Invoke() (extension method) as follows:

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

Then use AsExpandable() on your DbSet<T>:

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

Read this to understand the problem with nested expressions.



来源:https://stackoverflow.com/questions/29960715/how-to-define-expression-selection-nested-one-to-one-relationship-in-entity-fram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!