我正在构建表达式树:
{x => x.principal_info.First().agent_for_property_info}
它按预期工作。
实际上,我需要将其转换为IEnumerable
而不是ICollection
,如下所示。
这是可行的方法:
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;
}
在表达式中,我得到了有效的lambda表达式:
当我进行强制类型转换时:{x => x.principal_info.First().agent_for_property_info}
var expRight = (Expression<Func<T, IEnumerable<K>>>)expression;
我遇到了一个异常:
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]]]'.
我知道ICollection
继承自IEnumerable
,假设这是一个相当容易修复的问题。
我进行了大量研究,但没有找到将ICollection<T>
强制转换为IEnumerable<T>
的解决方案,甚至不确定是否可能实现这一点?
事实上,编译器可以隐式地将其转换,因为以下代码行是有效的:
var queryData1 = new QueryData<contact_info, IEnumerable<property_info>>()
{
WhereClause = expression,
SelectClause = info => info.principal_info.First().agent_for_property_info
};
作为这个表达式的一种
ICollection
类型:
info => info.principal_info.First().agent_for_property_info
ICollection<T>
转换为IEnumerable<T>
。你正在尝试转换(手摆两下)将生成ICollection<T>
的 委托。你不需要对 它 进行强制转换,而是需要在它生成一个结果时对其进行强制转换,这表明你将要编写(部分)表达式树来实现你想要的功能(如果这是你想走的路线)。 - Damien_The_Unbeliever