How to use C# 8.0 Nullable Reference Types with Entity Framework Core models?

.net-core c# entity-framework entity-framework-core nullable-reference-types

Question

I am enabling C# 8.0 Nullable Reference Types on a .NET Core 3.0 project. The project uses Entity Framework Core 3.0 to access database.

The following is a data model whose Title should not be null.

public class Vehicle
{
    public int Id { get; private set; } 

    public string Title { get; private set; }

    // Entity Framework Core is instructed to bind to the private _drivers field in a configuration builder
    private readonly List<Driver> _drivers = new List<Driver>();
    public IReadOnlyCollection<Driver> Drivers => _drivers.AsReadOnly();

    private Vehicle() 
    {
    }

    public Vehicle(string title) 
    {
        this.Title = title;
    }

    public void AddDriver(string name)
    {
         this._drivers.Add(new Driver(name));
    }
 }

// A foreign column is defined in a configuration builder
public class Driver
{
    public int Id { get; private set; } 

    public string Name { get; private set; }

    private Driver() 
    {
    }

    public Driver(string name) 
    {
        this.Name = name;
    }
 }

Own code is supposed to use the public constructors only while the private constructors are there just to allow Entity Framework Core and (potentially also) serialization to bind values from database to these classes/models. The public constructor might have different structure, list and types of arguments than which properties the model has (for example, it might also contains arguments for the first required child, it might have some arguments optional etc.).

However, the compiler generates CS8618 Non-nullable field is uninitialized. Consider declaring as nullable. on the private constructors.

I am able to disable CS8616 for the private constructors by #pragma warning disable CS8618 but I do not consider that as a good idea.

How it is supposed to use C# 8.0 Nullable Reference Types in this scenario? Or is my model bogus or violates best practices - how to do it properly?

Unfortunatelly, I have found not relevant docs or guidance.

1
16
9/30/2019 5:12:57 PM

Popular Answer

There is no proper way to handle non-nullable navigational properties.

  1. Documentation suggests two ways and both are not type safe. Use a backing field and throw InvalidOperationException. It is unclear how it differs from doing nothing and have a NullReferenceException
  2. Suppress it with null forgiving operator

Official documentation link: https://docs.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types#non-nullable-properties-and-initialization

6
10/2/2019 9:51:18 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow