Child objects do not load when a query joins tables

I have a many-to-many relationship in which Content has ContentTags pointing to a tag. I created the corresponding [Include] attributes for my objects to create properties.

If I write enumerate ObjectContext.Contents.Include("ContentTags.Tag")then I will get ContentTags and tags as expected. When I use a connection, however Content Content is missing in my Content object:

var contentsForTag =
    from c in ObjectContext.Contents.Include("ContentTags.Tag")
    join ct in ObjectContext.ContentTags on c.Id equals ct.ContentId
    join t in ObjectContext.Tags on ct.TagId equals t.Id
    where t.Name.ToLower().Contains(lowerTag)
    select c;

Any ideas what is going on here?

+3
source share
3 answers

, , , - . , EF , lowerTag, Include , . , EF , . ,

var contentsForTag =
    from c in ObjectContext.Contents.Include("ContentTags.Tag")
    where c.ContentTags.Any(ct => ct.Tag.Name.ToLower().Contains(lowerTag))
    select c;
+2

:

var anonType =
    from c in ObjectContext.Contents
    join ct in ObjectContext.ContentTags on c.Id equals ct.ContentId
    join t in ObjectContext.Tags on ct.TagId equals t.Id
    where t.Name.ToLower().Contains(lowerTag)
    select new { Contents = c, ContentTags = ct, Tags = t }).AsEnumerable();

IList<Contents> contentsForTag = anonType.Select(c => c.Contents).ToList();

, EF , . , EF , , . , .

+1

It sounds like a "lazy load" and the difference is "looking forward." A collection of tags for the Content class is stored in a child table. Many ORMs, including EF, try to lazily load collections and other many-to-one links, because they don’t know if you need them, and that would be a waste of bandwidth if you didn’t. However, this means that your tags are not available in the extracted instances. To tell L2E that yes, you really need tags, you indicate that the link to child objects must be “eagerly” passed when building the context.

0
source

Source: https://habr.com/ru/post/1796099/


All Articles