Where did the overload of DbQuery.Include() go that takes a lambda?

C#Entity Framework

C# Problem Overview


I just declared some code-first models for a new project that uses EntityFramework.

public class BlogEntry
{
    public long Id { get; set; }
    public long AuthorId { get; set; }
    public DateTime PublishedStamp { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }

    public virtual User Author { get; set; }
}

public class User
{
    public long Id { get; set; }
    public string Email { get; set; }
    // ...
}

class BlogDb : DbContext
{
    public DbSet<BlogEntry> Entries { get; set; }
    public DbSet<User> Users { get; set; }
}

Now suppose I want to retrieve the 10 most recent blog entries:

var entries = new BlogDb().Entries.OrderByDescending(...).Take(10).ToList();

The problem now is that accessing entry.Author will cause another database query. You wouldn’t want a separate such query for every blog entry. Now, it is my understanding that the purpose of Include is exactly this case, so I can say:

var entries = new BlogDb().Entries.Include(e => e.Author).(...).ToList();

However, that method doesn’t seem to exist. There is only an Include(string), like this:

var entries = new BlogDb().Entries.Include("Author").(...).ToList();

but this is annoying because it’s not compile-time checked and will be missed by the rename refactoring. Surely the version with the lambda is the “correct” approach.

Where did that method go? Is it no longer included in EntityFramework?

(I know that I can write an extension method for myself to achieve this, so you don’t have to. I’d just like to know whether I’m missing something.)

C# Solutions


Solution 1 - C#

using System.Data.Entity;

It's in EF v4.1 and above, but you need a reference as it is an extension method.


Edit (thanks to @EastonJamesHarvey)

If using EF Core the import should be:

using Microsoft.EntityFrameworkCore;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimwiView Question on Stackoverflow
Solution 1 - C#Not lovedView Answer on Stackoverflow