Published:

.NET + Entity Framework - Fix for Non-nullable property '...' must contain a non-null value in EF DbContext

I recently enabled nullable reference types on a .NET 7 project with the following setting in my .csproj file:

<Nullable>enable</Nullable>

The project uses Entity Framework and contains a DataContext class that extends from DbContext, and includes the following DbSet property named Accounts:

public DbSet<Account> Accounts { get; set; }


Entity Framework nullable reference warning

After enabling nullable reference types on the project the DbContext class started showing the following warning about the DbSet property in VS Code:

Non-nullable property 'Accounts' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.


How to fix the warning

The solution was to update the Accounts property to create and return the DbSet in the property getter with the DbContext.Set<TEntity>() method:

public DbSet<Account> Accounts => Set<Account>();


Example DbContext class

This is the example DbContext class with the fix applied to the DbSet property:

namespace WebApi.Helpers;

using Microsoft.EntityFrameworkCore;
using WebApi.Entities;

public class DataContext : DbContext
{
    public DbSet<Account> Accounts => Set<Account>();
    
    private readonly IConfiguration Configuration;

    public DataContext(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // connect to sqlite database
        options.UseSqlite(Configuration.GetConnectionString("WebApiDatabase"));
    }
}

For more info on working with nullable reference types in .NET see https://learn.microsoft.com/ef/core/miscellaneous/nullable-reference-types.

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some .NET Help?

Search fiverr to find help quickly from experienced .NET developers.



Supported by