[英]Can't convert ICollection<t> to IEnumerable<t>
I am building the expression tree: 我正在构建表达式树:
{x => x.principal_info.First().agent_for_property_info}
{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. 事实上,我需要将它转换为
IEnumerable
而不是ICollection
,你可以在这里看到。
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: 在表达式中,我得到有效的lambda表达式:
{x => x.principal_info.First().agent_for_property_info}
{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. 我知道
ICollection
继承自IEnumerable
假设它很容易修复。
I researched a lot but didn't find the solution how to cast ICollection<T>
to IEnumerable<T>
or if this even possible? 我研究了很多,但没有找到解决方法如何将
ICollection<T>
为IEnumerable<T>
或者这是否可能?
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
: 由于此表达式是一种
ICollection
:
info => info.principal_info.First().agent_for_property_info
info => info.principal_info.First()。agent_for_property_info
After a few hours of researching, trying different approaches, I came up with Idea, trying to overcome this exception. 经过几个小时的研究,尝试不同的方法,我提出了想法,试图克服这个异常。 So the workaround I use was the suggestion from the comments:
所以我使用的解决方法是评论中的建议:
x => x.principal_info.First().agent_for_property_info.Select(x4 => x4)
x => x.principal_info.First()。agent_for_property_info.Select(x4 => x4)
Here what I have added while building an expression: 这是我在构建表达式时添加的内容:
var result1 = Expression.Call(
typeof(Enumerable), "Select", new Type[] { elementResultType, elementResultType },
resultProperty, resultExpr);
I actually didn't find the solution, but if someone will encounter such problem, maybe this answer could save his time. 我实际上没有找到解决方案,但如果有人遇到这样的问题,也许这个答案可以节省他的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.