Search code examples
c#entity-framework-core

Why does Entity Framework return an empty collection instead of a null for a property?


I have an Entity Framework model that has the following property:

public List<MapInterestToVanType>? VanMapEventTypes { get; set; }

I then read the object using:

var @event = await dbContext.Events
    .Include(e => e.ApptShifts)
    .Include(e => e.Occurrences)
    .Include(e => e.Owner)
    .Include(e => e.Parent)
    .FirstOrDefaultAsync(e => e.Id == updateEvent.EventId, stoppingToken);

This returns @event.Parent.VanMapEventTypes == an empty of List<MapInterestToVanType>().

If I add:

var @event = await dbContext.Events
    .Include(e => e.ApptShifts)
    .Include(e => e.Occurrences)
    .Include(e => e.Owner)
    .Include(e => e.Parent)
    .ThenInclude(o => o.VanMapEventTypes)
    .FirstOrDefaultAsync(e => e.Id == updateEvent.EventId, stoppingToken);

It then returns @event.Parent.VanMapEventTypes with the expected 11 items in the List<MapInterestToVanType>().

Why does it not return @event.Parent.VanMapEventTypes == null in the first call?


public class Organization
{
    public int Id { get; private set; }
    public List<MapInterestToVanType>? VanMapEventTypes { get; set; }
    // lots of other properties

    public Organization(string uniqueId)
    {
        ArgumentException.ThrowIfNullOrEmpty(uniqueId);

        Enabled = true;
        Private = false;
        Deleted = false;

        UniqueId = uniqueId;
        // initialize this because the data is in the Campaign table so logically its never null.
        Address = new Address();

        VanMapEventTypes = new List<MapInterestToVanType>();
    }
}

public class Event
{
    public int Id { get; private set; }
    public Organization Parent { get; set; }
    // lots of other properties
}

public class MapInterestToVanType
{
    public int Id { get; private set; }
    public string InterestName { get; set; }
    public string VanEventTypeName { get; set; }
}

Solution

  • The issue is my constructor has:

    VanMapEventTypes = new List<MapInterestToVanType>();
    

    so event if there is no Include(e => e.VanMapEventTypes), it will still create the empty collection. I removed that line of code and now it works as I expected.