-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

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.