Entity Framework does not eager load when using Include()

c# entity-framework entity-framework-6


I have a simple model and a simple query. I'm trying to get EF to eager load my navigation properties:

// Document object has a navigation property "DocType" of type DocType
// DocType object has a navigation property "Documents" of type ICollection<Documents> that is NOT virutal

context.Set<Document>().Where(d=>d.Id == id).Include(d=>d.DocType).SingleOrDefault();

The problem is that this doesn't actually eager load DocType. The stranger thing is that excluding the Include() call does load the DocType property, but as a second query.

I've looked all around and applied every fix I found:

  1. Added a call to Include()
  2. Removed virtual from both navigation properties

Any idea what's going on here? Is it possible to coerce EF to merge this into a single query that's eager loaded?

EDIT: This is my data model:

namespace Data.Models {

    class Document {
        public int Id { get; set;}
        public int TypeId { get; set; }
        public DocType DocType { get; set; }

    class DocType {
        public int Id { get; set; }
        public string FullName { get; set; }
        public ICollection<Document> Documents { get; set; }

namespace Data.Mappings {

    internal class DocumentTypeConfiguration : EntityTypeConfiguration<Document> {

        public DocumentTypeConfiguration() {

            HasKey(m => m.Id);

            Property(m => m.Id)

            Property(m => m.TypeId)

            HasRequired(d => d.DocType)

    internal class DocTypeTypeConfiguration : EntityTypeConfiguration<DocType> {

        public DocTypeTypeConfiguration() {

            HasKey(m => m.Id);

            Property(m => m.Id)

            Property(m => m.FullName)

The oddest thing is that when I call:


The DocType properties are populated, but EF does this by executing two separate queries. Is it possible to design this in such a way the EF understands that this can be accomplished with one query?

EDIT 2: This question seems to address the same problem, but only states the calling Include() fixes it, which is not working in my case.

5/23/2017 11:53:39 AM

Popular Answer

In general case, using string instead of expression (as mention @vanraidex) is not a good practice. In general case. However, when using third party providers (e.g. Oracle Provider) it can be the only way to get correct sql (with joins).

So, if you using special Data Provider and .Include() method doesn't work, try to use string instead of expression.

context.Documents.Where(d=>d.Id == id).Include("DocType").SingleOrDefault();
7/3/2017 4:55:19 AM

Related Questions


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