问题
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