Where did the lambda-accepting overload of DbQuery.Include() go?

c# entity-framework

Question

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.)

1
71
3/25/2012 12:38:04 AM

Accepted Answer

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;
103
11/14/2018 3:35:43 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow