Brian Turner

Brian Turner

  • NA
  • 74
  • 14.8k

Nullable / Optional Foreign Key using EF Core 5

Jan 29 2021 7:51 PM

Hi All,

I have been struggling to find an answer to having a nullable / optional foreign key using .net core 5 and EF core 5.

The relationship is a one-to-many and the parent table does not always require the foreign key making it optional.

I am migrating a desktop app to a .net core 5 web app so my DB parent table has a majority of null values for the foreign key column.

The problem comes in when I want to view any parent table records with a null foreign key value as EF Core simply ignores the records and does not display anything.

When the parent table foreign key value is populated the records show up.

I have tried to simply make the foreign key nullable in the model as below but I get a null exception error at run time.

[ForeignKey("CesArea")]

public int? AreaID { get; set;

public virtual CesArea CesArea { get; set; }

Any help would be greatly appreciated!


Answers (3)