dimanche 11 octobre 2015

Linq To SQL : Include Child Collection of Child

So I have a sqlite database. Foo has a 1 to 1 relationship to a type Bar. Bar has a 1 to many relationship with type Baz

I am using LinqToSql.

If I use a query to get all Bars with children Baz objects like this:

        IEnumerable<MeleeWeapon> returnValue;
        using (var connection = GetDatabaseConnection())
        using (var context = new DataContext(connection))
        {
            context.DeferredLoadingEnabled = false;

            var options = new DataLoadOptions();
            options.LoadWith<MeleeWeapon>(mw => mw.Attacks);

            context.LoadOptions = options;

            var query =
                from
                    meleeWeapon in context.GetTable<MeleeWeapon>() 
                select
                    meleeWeapon;


            returnValue = query.ToArray();

        }

        return returnValue;

I am successful.

If I use a query to get all foos that have a bar like this:

        IEnumerable<Item> returnValue;
        using (var connection = GetDatabaseConnection())
        using (var context = new DataContext(connection))
        {
            context.DeferredLoadingEnabled = false;

            var options = new DataLoadOptions();
            options.LoadWith<Item>(i => i.MeleeWeaponInformation);

            context.LoadOptions = options;

            var query =
                from
                    item in context.GetTable<Item>()
                where
                    item.MeleeWeaponInformation.Any()
                select
                    item;


            returnValue = query.ToArray();

        }

        return returnValue;

I am successful.

Inexplicably, if I use a query to get all foos that contain bars, with all bats that belong to said bars like this:

        IEnumerable<Item> returnValue;
        using (var connection = GetDatabaseConnection())
        using (var context = new DataContext(connection))
        {
            context.DeferredLoadingEnabled = false;


            var options = new DataLoadOptions();
            options.LoadWith<Item>(i => i.MeleeWeaponInformation);
            options.LoadWith((MeleeWeapon mw) => mw.Attacks);


            context.LoadOptions = options;

            var query =
                from
                    item in context.GetTable<Item>()
                where
                    item.MeleeWeaponInformation.Any()
                select
                    item;


            returnValue = query.ToArray();

        }

        return returnValue;

I get an invalidCastException on the line with query.ToArray()

The one guess I had is that two of the tables have a column named Id (Foo.Id and Baz.Id; Bar being a 1 to 1 with foo, the foreign/primary key is Bar.Foo) Did I do something wrong? Is getting Parent.Child.Grandchild impossible in LinqToSql? Is it a problem with SQLite?

Aucun commentaire:

Enregistrer un commentaire