19

I can include only related entities.

using (var context = new BloggingContext()) 
{ 
    // Load all blogs, all related posts
    var blogs1 = context.Blogs 
                       .Include(b => b.Posts) 
                       .ToList(); 
}

However, I don't need entire BlogPost entity. I'm interested only in particular properties, e.g:

using (var context = new BloggingContext()) 
{ 
    // Load all blogs, all and titles of related posts
    var blogs2 = context.Blogs 
                       .Include(b => b.Posts.Select(p => p.Title) //throws runtime exeption
                       .ToList(); 

    foreach(var blogPost in blogs2.SelectMany(b => b.Posts))
    {
        Console.Writeline(blogPost.Blog.Id); //I need the object graph
        Console.WriteLine(blogPost.Title); //writes title
        Console.WriteLine(blogPost.Content); //writes null
    }
}
2
  • are you using entity framework core? Jan 26, 2018 at 13:59
  • yes, latest stable version
    – Liero
    Jan 26, 2018 at 13:59

4 Answers 4

11

You either use Include which loads the entire entity, or you project what you need to a .Select:

var blogs2 = context.Blogs 
    .Select(x => new 
    {
        BlogName = x.BlogName, //whatever
        PostTitles = x.Post.Select(y => y.Title).ToArray()
    }) 
   .ToList(); 

Or, you could do something like this:

var blogs2 = context.Blogs 
    .Select(x => new 
    {
        Blog = x,
        PostTitles = x.Post.Select(y => y.Title).ToArray()
    }) 
   .ToList(); 

A Select is always better when you don't need the entire child, as it prevents querying unneeded data.

2
  • Thx for suggestion. Using custom select with anonymous types is simplest possible scenario, but I need the blog entity and it's object graph
    – Liero
    Jan 26, 2018 at 14:12
  • @Liero Well, you have to load the entire entity then Jan 26, 2018 at 14:13
6

In fact what you want is: split an entity in a common, representational part and a special part that you don't always want to pull from the database. This is not an uncommon requirement. Think of products and images, files and their content, or employees with public and private data.

Entity framework core supports two ways to achieve this: owned type and table splitting.

Owned type

An owned type is a type that's wrapped in another type. It can only be accessed through its owner. This is what it looks like:

public class Post
{
    public int ID { get; set; }
    public Blog Blog { get; set; }
    public string Title { get; set; }
    public PostContent Content { get; set; }
}

public class PostContent
{
    public string Content { get; set; }
}

And the owned-type mapping:

modelBuilder.Entity<Post>().OwnsOne(e => e.Content);

Where Blog is

public class Blog
{
    public Blog()
    {
        Posts = new HashSet<Post>();
    }
    public int ID { get; set; }
    public string Name { get; set; }

    public ICollection<Post> Posts { get; set; }
}

However, as per the docs:

When querying the owner the owned types will be included by default.

Which means that a statement like...

var posts = context.Posts.ToList();

...will always get you posts and their contents. Therefore, owned type is probably not the right approach for you. I still mentioned it, because I found out that when Posts are Included...

var blogs = context.Blogs.Include(b => b.Posts).ToList();

...the owned types, PostContents, are not included (DISCLAIMER: I'm not sure if this is a bug or a feature...). In this case, when the owned types should be included a ThenInclude is required:

var blogs = context.Blogs.Include(b => b.Posts)
        .ThenInclude(p => p.Content).ToList();

So if Posts will always be queried through Blogs, owned type may be appropriate.

I don't think this applies here, but it does when children having owned types have an identifying relationship with their parents (classical example: Order-OrderLine).

Table splitting

With table splitting a database table is split up into two or more entities. Or, from the objects side: two or more entities are mapped to one table. The model is almost identical. The only difference is that PostContent now has a required primary key property (ID, of course having the same value as Post.ID):

public class Post
{
    public int ID { get; set; }
    public Blog Blog { get; set; }
    public string Title { get; set; }
    public PostContent Content { get; set; }
}

public class PostContent
{
    public int ID { get; set; }
    public string Content { get; set; }
}

And the table-splitting mapping:

modelBuilder.Entity<Post>()
    .HasOne(e => e.Content).WithOne()
    // or .WithOne(c => c.Post) if there is a back reference
    .HasForeignKey<PostContent>(e => e.ID);
modelBuilder.Entity<Post>().ToTable("Posts");
modelBuilder.Entity<PostContent>().ToTable("Posts");

Now Posts will always be queried without their contents by default. PostContent should always be Include()-ed explicitly.

Also, PostContent can now be queried without its owner Post:

var postContents = context.Set<PostContent>().ToList();

I think this is exactly what you're looking for.

Of course you can do without these mappings if you'll always use projections when you want to fetch posts without contents.

0
5

You can try this :

using (var context = new BloggingContext())
{
    var blogProps = context.Blogs
        .SelectMany(b => 
            b.Posts.Select(p => 
                new { Blog = b, PostTitle = p.Title }
            )
         )
        .ToList();
}

EDIT
If you want to stick to your data model, you could try something like this :

using (var context = new BloggingContext())
{
    var blogProps = context.Blogs
        .Select(b => 
            new Blog 
            { 
                Name = b.Name, 
                Posts = new List<Post>(b.Posts.Select(p => 
                    new Post 
                    { 
                        Title = p.Title 
                    })
            }
        )
        .ToList();
}
8
  • Ok, but I actually need blog entities as well. I know I can solve it using new anonymous types, but I was curious whether it could work like that
    – Liero
    Jan 26, 2018 at 14:08
  • If you need Blog also, you can just add it to the anonymous type. Are you trying to do that in another way?
    – Atlasmaybe
    Jan 26, 2018 at 14:10
  • Or maybe you don't want to use anonymous types and sticks to your data model? So you want to have some properties te be null ?
    – Atlasmaybe
    Jan 26, 2018 at 14:12
  • Yes, I would like to stick with my data model if possible
    – Liero
    Jan 26, 2018 at 14:13
  • @Liero You can, but it's lot of work. You have basically to build each entity by yourself with anonymous constructors like new Blog { Name = b.Name }
    – Atlasmaybe
    Jan 26, 2018 at 14:15
-1

I think there's a much easier way to do this. Projection is nice and all, but what if you want all the columns from your parent entity and most of them from the child? When those types have a lot of properties, using projection means you have a lot of lines of code to write just to select everything you want except the few that you don't. Well, since using projection means your entities won't be tracked, it's much easier to use .AsNoTracking() and then just empty out the things you don't want.

var foos = await _context.DbSet<Foo>()
    .AsQueryable()
    .Where(x => x.Id == id)
    .Include(x => x.Bars)
    .AsNoTracking()
    .ToListAsync();

foreach (var foo in foos)
{
    foreach (Bar bar in foo.Bars)
    {
        bar.Baz = null;
    }
}
5
  • You either use Include which loads the entire entity, or you project what you need using Select. In your code you added .Include(x => x.Bars) which loads navigation collection Foo.Bars and for each record it load all properties including Baz. So setting Baz to null after fetching it from the database is meaningless. Nov 9, 2022 at 9:15
  • @AdiletSoronov My point was that if you have an entity that has a ton of properties and you want everything but a few, it's a lot less code to null out the ones you don't want instead of selecting all of the ones you do. Nov 15, 2022 at 16:52
  • 1
    respectfully that's not how EF Core works, there's no way to exclude some properties from loading. In your code you are loading all properties and then setting some to null, which is pointless. Another solution would be "Onwed Type", loading owner entity will also load dependent entity but it's also possible to change that behavior. modelBuilder.Entity<OwnerEntity>(). Navigation (x => x.DependentEntity).AutoInclude(false) Nov 17, 2022 at 13:55
  • @AdiletSoronov I do indeed understand that the SQL generated by EF Core will select these columns, but again my point was you write a lot less code doing it this way. This is useful for when your entity has a lot of properties and you want almost all of them except for one or two. The point isn't to reduce the amount of data traveling over the wire, but to save you from having to list out every single other property in your Select() list. It also helps when you add more properties to the entity and those also need to be included: you'll get them automatically without changing the list. Nov 20, 2022 at 18:49
  • 1
    well, if that works for you then it's okay, I think. Just yesterday I was working on a project and the load time for the site was 5 seconds, because the code was loading all records with images but only showed 10 records and didn't show images at all. Sometimes loading everything is okay for now, but later you or someone else may add new properties that you don't need. I hope you'll do great Nov 23, 2022 at 1:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.