efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Include->ThenInclude for a collection

Open sitefinitysteve opened this issue 10 years ago • 50 comments

Steps to reproduce

This could be any structure, basically an object which has a collection as a nav property

var educator = this.Context.Educators.Include(x => x.Studies) //List<Study>
                                                 .Include(x => x.Sites) //List<Site>
                                                 .Single(x => x.Id == id);

This returns what I want, however if I then try to loop through

 @foreach (var s in Model.Sites)
{
                                        <tr>
                                            <td>
                                                @s.Site.Name //WILL CRASH
                                                @s.SiteId //JUST FINE
                                            </td>
                                        </tr>
}

The issue

Every example for Include->ThenInclude seems to assume the nav properties are simple objects not collections. In the "ThenInclude" how to we populate each array items objects?

-- No Exception, outside of NULL REF --

Further technical details

EF Core version: 1.0.1 Operating system: Win10 Visual Studio version: 2015

Other details about my project setup:

sitefinitysteve avatar Sep 17 '16 03:09 sitefinitysteve

The query written above will populate Studies & Sites navigations for educator but in the for loop you are trying to access s.Site.Name. If the Site is navigation property then it won't be loaded as it wasn't specified during the query so null ref is expected. You need to use ThenInclude for that.

Every example for Include->ThenInclude seems to assume the nav properties are simple objects not collections. In the "ThenInclude" how to we populate each array items objects?

There is no such assumption. Rather when navigation is collection, to load nav props for each collection item ThenInclude is required. See the examples at https://ef.readthedocs.io/en/latest/querying/related-data.html#including-multiple-levels

smitpatel avatar Sep 20 '16 18:09 smitpatel

I suppose this is what the problem is, how would you structure a ThenInclude for a collection?

Example:

var data = context.Blogs.Include(x => x.Post).ThenInclude(x => x.Author)

So the second nested level is just another simple object, easy...but how would you operate on a collection on that level to say like "For each study in studies, ThenInclude it's site object"

sitefinitysteve avatar Sep 20 '16 18:09 sitefinitysteve

@sitefinitysteve - Can you share the classes (only navigation properties needed) and which are the navigations you want to eager load?

smitpatel avatar Sep 20 '16 19:09 smitpatel

Here is the code you want

this.Context.Educators.Include(x => x.Studies).ThenInclude(x => x.Sites)

rowanmiller avatar Sep 21 '16 19:09 rowanmiller

@rowanmiller I'm sorry I dont think I'm explaining this properly

(non-important props removed)

    public class Educator
    {
        public virtual List<StudyEducator> Studies { get; set; }
    }

So yes this:

this.Context.Educators.Include(x => x.Studies)

will give me a list of StudyEducator items

However each StudyEducator object has navigation properties as well

    public class StudyEducator
    {
        public int StudyId { get; set; }
        public virtual Study Study { get; set; }

        public int EducatorId { get; set; }
        public virtual Educator Educator { get; set; }
    }

So a ThenInclude is operating on the List and you get this image

Where instead I want to say "Foreach StudyEducator hydrate it's Study nav property as well"

sitefinitysteve avatar Sep 21 '16 19:09 sitefinitysteve

@sitefinitysteve that's a bug in IntelliSense (we've passed it to the IntelliSense team to look at). The compiler handles it just fine though, so you'll just need to type out that code without using IntelliSense.

rowanmiller avatar Sep 21 '16 21:09 rowanmiller

@rowanmiller Amazing... you have no idea the time I burned on this one, OY... thanks 👍

sitefinitysteve avatar Sep 22 '16 02:09 sitefinitysteve

Intellisense bug is https://github.com/dotnet/roslyn/issues/8237. @sitefinitysteve feel free to post your feedback there.

divega avatar Sep 22 '16 06:09 divega

Yeah I hit the same problem. I'm on VS 2017 and .Net core 1.1.1. If that intellisense gets corrected would be great.

hawkpgl avatar Mar 16 '17 11:03 hawkpgl

Still an issue in Visual Studio 2017 Version 15.2 (26430.12). Intellisense suggest me that we've a list. When I blind type the attribute from the foreign relation, the IDE get it. But it's required to type the attribute manually without intellisense. Would be nice to have this fixed in VS, since Intellisense is a great feature of VS.

DMW007 avatar Jun 24 '17 12:06 DMW007

@DMWOO7 a fix has been delayed to a future version. Please provide any feedback in the Roslyn issue linked above.

divega avatar Jun 25 '17 04:06 divega

@rowanmiller you saved my day

manojgarg avatar Jul 17 '17 07:07 manojgarg

Yes please fix this. While it's frustrating to deal with Intellisense that won't come up, it's completely different when the Intellisense is wrong.

We trust the Intellisense. It has to be right.

I ran into this today. Thanks for the great question and answers here.

ryansealy avatar Jul 20 '17 17:07 ryansealy

@ryansealy We appreciate the feedback, but please comment on https://github.com/dotnet/roslyn/issues/8237. That is the issue that needs to get fixed for this to work.

ajcvickers avatar Jul 20 '17 18:07 ajcvickers

I encountered this with .NET Core 2.0 on Linux and EF Core 2.0, in F# -- but during compilation, not auto-completion.

schema (most fields omitted):

    public class Schema
    {
        public List<Entity> Entities { get; set; }
    }

    public class Entity
    {
        public int? SchemaId { get; set; }
        public Schema Schema { get; set; }
        public List<Field> Fields { get; set; }
    }

    public class Field
    {
        [Required]
        public int EntityId { get; set; }
        public Entity Entity { get; set; }
    }

code (type annotation is given because otherwise the error is about unknown field):

    let q = db.Schemas
                .Include(fun sch -> sch.Entities)
                .ThenInclude(fun (ents : Entity) -> ents.Fields)
                .ToList()

error:

/home/app/project/FunDB/src/FunQL/Meta.fs(98,35): error FS0001: This expression was expected to have type    'System.Collections.Generic.List<Entity>'    but here has type    'Entity' [/home/app/project/FunDB/FunDB.fsproj]

abbradar avatar Nov 21 '17 14:11 abbradar

@abbradar This seems like a different issue from the one discussed here. Can you please file a new issue together with complete code listing or project to reproduce what you are seeing?

ajcvickers avatar Nov 21 '17 16:11 ajcvickers

@abbradar @ajcvickers F# is not able to automatically pick the overload method with following signature (please, note the IEnumerable<TPreviousProperty> for the type returned from previous .Include() call):

ThenInclude<TEntity,TPreviousProperty,TProperty(IIncludableQueryable<TEntity,IEnumerable<TPreviousProperty>>,Expression<Func<TPreviousProperty,TProperty>>)

which would convert from List<TEntity> to TEntity for chained ThenInclude.

I suppose that this happens because F# won't automatically upcast List<T> to IEnumerable<T>. Explicitly upcasting the .Include() lambda to IEnumberable<T> seems to resolve the issue:

let q =
    db.Schemas
       .Include(fun sch -> sch.Entities :> IEnumerable<_>)
           .ThenInclude(fun (ents : Entity) -> ents.Fields)
       .ToList()

Hope this helps!

manchoz avatar Feb 28 '18 13:02 manchoz

@rowanmiller I spend tons of hours because of that IntelliSense bug.

irensaltali avatar Apr 03 '18 16:04 irensaltali

@rowanmiller Many thanks for the info, it really helped - one would think that after two years this would be fixed 😕

Programm3r avatar Jul 11 '18 09:07 Programm3r

This got me today too. =/

devsoitic12 avatar Aug 03 '18 12:08 devsoitic12