Search code examples
c#.net-coreentity-framework-coremany-to-manynavigation-properties

How to make inverse properties in ef core not return null but empty list


I have two simple tables - TaskItem and TaskList - that have many-to-many relationship through table TaskInList that only contains the foreign keys and OrderNo.

On TaskInList I have made properties:

    [ForeignKey("TaskID")]
    public TaskItem Task { get; set; }
    [ForeignKey("ListID")]
    public TaskList List{ get; set; }

On TaskItem:

    [InverseProperty("Task")]
    public virtual List<TaskInList> TasksInLists { get; set; }

On TaskList:

    [InverseProperty("List")]
    public virtual List<TaskInList> TasksInLists { get; set; }

When there are objects that are related I get a list of related objects, but when there are none, I get a null. I guess I can work around it, but my question is, is there an option to, by default, initialize the inverse properties to empty lists, not null, if there are no related objects?

I am learning ef core so I want to do it the right way.


Solution

  • Initialize the list in the constructor.