Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Entity Framework .Include Eager load does not load entity

My first question - be kind :-).

In the code below, I am attempting to reference an "Include(d)" entity (Schedules) to obtain its Name property. In EF 6, both "schedule" and "schedule_2" return the correct value of Name. In EF Core, "schedule" returns NULL and "schedule_2" returns the correct value of Name.

I do not understand why I should have to load the "schedules" List. Shouldn't the .Include force an Eager Load of the Schedules for each Election such that each Election Schedule's Name property would be available for the "schedule" assignment?

// Relevant Model entities in database
//         DbSet<Election> Elections { get; set; }
//
// The following are the related classes defined in the database context...
public class Election
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Schedule> Schedules { get; set; }
}
public class Schedule
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public int? CfsElectionId { get; set; }
    public string Name { get; set; }

    [Required] // sets cascade delete
    [ForeignKey("CFSElectionID")]
    public virtual Election Election { get; set; }
}

class Program
{
    static void Main()
    {
        var db = new FfmsDbContext();
        var elections = db.Elections
            .Include(i => i.Schedules)
            .ToList();

        //The following returns NULL?
        var schedule = elections.First().Schedules?.First().Name ?? "NULL";

        var schedules = db.Schedules
            .ToList();

        //The following returns the correct Name property?
        var schedule_2 = elections.First().Schedules?.First().Name ?? "NULL";

        Console.WriteLine($@"sched: {schedule}");
        Console.WriteLine($@"schedules.First().Name: {schedules.First().Name}");
        Console.WriteLine($@"sched2: {schedule_2}");

        Console.WriteLine("Done...");
        Console.ReadLine();
    }
}

/*
  Output...
    sched: NULL
    schedules.First().Name: Candidates
    sched2: Candidates
    Done...
*/
like image 640
Fred Schmidt Avatar asked Jun 04 '26 19:06

Fred Schmidt


1 Answers

Turns out that my problem ended up being in the References of the Class.

I had accidentally chosen System.Data.Entity as the offered choice for .Include.

The correct reference should have been Microsoft.EntityFrameworkCore.

Once I adjusted the reference, the .Include worked as desired.

like image 187
Fred Schmidt Avatar answered Jun 06 '26 10:06

Fred Schmidt