Entity Framework Core 2 is not eagerly loading Included entity

.net-core c# entity-framework entity-framework-core


I have some code which I'm upgrading from dotnetcore1.1 to dotnetcore2.0 (and correspondingly EF core from 1 to 2)

I have the following Model (anonymised, of course), and using Npgsql to talk to a postgres database.

public class Company
  [Key, Column("id")]
  public int Id { get; set; }

  [Column("name", TypeName = "VARCHAR")]
  public string Name { get; set; }

  public int SerialNumber { get; set; }

  public virtual CompanyTypeMarker CompanyTypeMarker { get; set; }

public class CompanyTypeMarker
    [Key, Column("serialnumber"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int SerialNumber { get; set; }

    public CompanyType CompanyType { get; set; } = CompanyType.Customer;

I have this LINQ query:

var company = await db.Companies
  .Include(c => c.CompanyTypeMarker)
  .FirstOrDefault(cc => cc.SerialNumber == serialNumber);

In dotnetcore1.1, the Company entity would load, and it's associated CompanyTypeMarker entity would also be loaded and accessible via the Company.CompanyTypeMarker property

In dotnetcore2.0, the Company entity loads, but the Company.CompanyTypeMarker entity is null.

Looking at the log output, EF core is generating the following SQL:

  SELECT "c"."id", "c"."name", "c"."serialnumber", "c.CompanyTypeMarker"."serialnumber", "c.CompanyTypeMarker"."companytype"
  FROM "company" AS "c"
  INNER JOIN "companytypemarker" AS "c.CompanyTypeMarker" ON "c"."serialnumber" = "c.CompanyTypeMarker"."serialnumber"
  WHERE "c"."serialnumber" = @__SerialNumber_0

The generated SQL is evidence that EF core is picking up the navigation property, as it generates the correct sql JOIN for the correct properties... Just that when it comes back into C#, for some reason it's not picking up and populating the JOINed values.

Can anyone please help? As noted previously, this works in EF Core 1, and it seems like fairly standard use of navigation properties

2/1/2018 6:26:06 AM

Popular Answer

Ok, turns out I also had this in my OnModelCreating

  .Entity<Company>(entity => {
    entity.HasOne(x => { x.CompanyTypeMarker).WithOne().OnDelete(DeleteBehavior.Restrict);

I changed it to HasOne(...).WithMany() and it eagerly loads correctly now

2/1/2018 3:11:43 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