Published: January 18 2023

.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.

 


Need Some .NET Help?

Search fiverr for freelance .NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by