2

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 Answer 1

2

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.

2
  • Is it difficult to achieve this structure without using LinqKit?
    – Tom
    Apr 30, 2015 at 6:48
  • 1
    expr.Compile() returns a Func<Address, AddressDto> which EF cannot translate into SQL. Something must be done to overcome the problem and LinqKit does it elegantly and efficiently. If you don't like the idea of introducing new code and not going to write the workaround yourself, I assume you'll have to construct your Expression with regular Lambdas.
    – haim770
    Apr 30, 2015 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.