Combine two EF Queries, Unable to cast object of type System.Data.Entity.Infrastructure.DbQuery to System.Collections.Generic.IEnumerable

泪湿孤枕 提交于 2019-12-01 11:18:34

The enumerables cannot be concatenated because they are different anonymous types, due to having different property names.

One solution is to make the types match, e.g. you could replace this part:

Select PropertyDefinitions.PropertyDefName2, AdProductDefValues.DefValue2

With this

Select New With { .Name = PropertyDefinitions.PropertyDefName2, _
                  .Value = AdProductDefValues.DefValue2 }

And similarly:

Select New With { .Name = AdCustomProperties.PropertyTitle2, _
                  .Value = AdCustomProperties.PropertyValue2 }

The problem is that each sequence has a different type, so you can't just mash the 2 together as is. If you apply a .Cast<object>() to each one, before the Concat call, it should work as expected.

I think it would be cleaner if you separated the queries in different variables, then it would be a matter of:

DataSource = query1.Cast<object>().Concat(query2.Cast<object>());

Alternatively, you could create a method that returns the results as a non-generic IEnumerable:

private IEnumerable GetData()
{
    var query1 = [query1 logic];
    foreach (var item in query1)
        yield return item;

    var query2 = [query2 logic];
    foreach (var item in query2)
        yield return item;
}
...
DataSource = GetData();

This is not very common (to use untyped IEnumerable like this) but is useful with databinding since it is heavily based in reflection (thus the type of the items in the collection generally doesn't matter).

PS: Sorry for the C# specific syntax, as I don't work with VB and would probably just mess something in the process if I tried to write on that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!