How to debug and fix ‘Nullable object must have a value’ within Entity Framework Core?

There can be two answers.

Firstly, this may be probably because your query is returning NULL and the model is not accepting null.

Second fix may be, if you are using anonymous types, then try typecasting the query result into nullable type.

e.g.

Id = (int?) op.Id,

how to find which property is returning NULL?

You can enable SQL Profiler and check the SQL query which is getting executed. Copy the query into SSMS and see which values are NULL.
This may be helpful for you to decide out if you really need nullable typecast OR you want to change the query itself.

There is an issue on GitHub on this page.

Update: 05-July-2021: How to find which property is returning NULL ?

You can use simple logging feature (introduced in EF core 5.0) by calling EnableDetailedErrors method.
Below code example shows how to configure Simple Logging for showing logs on Console and it also enables detailed errors.
If you do not want to show logs on console, then you can pass an action delegate in LogTo call, which accepts a string as parameter. This delegate can then write logs to any destination of your choice.

Refer documentation for more details.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .LogTo(Console.WriteLine)
        .EnableDetailedErrors();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)