-2

I have this Linq query (Foo has a DateTime variable):

var tableFoo = context.GetTable<Foo>();
var tableBar = context.GetTable<Bar>();

var preselect = tableFoo.Where(o => o.Name == "");

List<Foo> foos = new List<Foo>();

foreach (Foo f in preselect) //System.InvalidCastException comes here at the second iteration (Unable to cast to DateTime)
{
    Foo foo = f;

    var subselect = tableBar.Where(o => o.Id == foo.Id);
    foreach (Bar bar in subselect)
    {
        foo.bars.Add(bar);
    }
    foos.Add(foo);
}

It works fine when preselect contains 1 object.
But if preselect contains more than 1 object, it won't work as expected. In the first iteration it works but in the second I get a System.InvalidCastException.
It has to do with the inner subselect because if I remove the inner foreach, it works perfectly.
I think it has to do with this. But I can't figure out what to change.

A subselect in the preselect wouldn't fit into my application architecture

Community
  • 1
  • 1
Bennik2000
  • 1,112
  • 11
  • 25

1 Answers1

0

I solved it like this (I know it is not very elegant):

var tableFoo = context.GetTable<Foo>();
var tableBar = context.GetTable<Bar>();

var preselect = tableFoo.Where(o => o.Name == "");

List<Foo> foos = new List<Foo>();

foreach (Foo f in preselect) //System.InvalidCastException comes here at the second iteration (Unable to cast to DateTime)
{
    Foo foo = f;

    foos.Add(foo);
}

foreach (Foo foo in foos)
{
    var subselect = tableBar.Where(o => o.Id == foo.Id);
    foreach (Bar bar in subselect)
    {
        foo.bars.Add(bar);
    }
}
Bennik2000
  • 1,112
  • 11
  • 25