I am building the expression tree:
{x => x.principal_info.First().agent_for_property_info}
It works as expected.
In fact, I need to convert it to IEnumerable instead of ICollection as you can see here.
Here is the method that works:
public Expression<Func<T, IEnumerable<K>>> GetGenericExpression<T, K>(bool first = false, params string[] properties)
{
var expression = GetNavigationPropertySelector<T, K>(typeof(T), first, properties);
var expRight = (Expression<Func<T, IEnumerable<K>>>)expression;
return expRight;
}
In the expression, I get the valid lambda expression:
{x => x.principal_info.First().agent_for_property_info}
When I am casting:
var expRight = (Expression<Func<T, IEnumerable<K>>>)expression;
I get an exception:
Unable to cast object of
type
'System.Linq.Expressions.Expression`1[System.Func`2[SomeModel1,
System.Collections.Generic.ICollection`1[SomeModel]]]'
to type
'System.Linq.Expressions.Expression`1[System.Func`2[SomeModel1
,System.Collections.Generic.IEnumerable`1[SomeModel]]]'.
I knew that ICollection inherits from IEnumerable assuming, that it something pretty easy to fix.
I researched a lot but didn't find the solution how to cast ICollection<T> to IEnumerable<T> or if this even possible?
In fact, the compiler can cast it implicitly as these lines are valid:
var queryData1 = new QueryData<contact_info, IEnumerable<property_info>>()
{
WhereClause = expression,
SelectClause = info => info.principal_info.First().agent_for_property_info
};
As this expression is a type of ICollection:
info => info.principal_info.First().agent_for_property_info