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; }
}
8
Although you declare MapInterestToVanTypes as nullable:
public List? VanMapEventTypes { get; set; }
You explicitly instantiate it to an empty list in the Organization constructor here:
VanMapEventTypes = new List();
If you are able to access @event.Parent here:
This returns @event.Parent.VanMapEventTypes == an empty of List()
Then you must have a non-null Organization object, which will contain at least an empty list, but never a null one.
2
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.