Home > Software engineering >  Deal with in Net 6's nullable and Entity Framework entities
Deal with in Net 6's nullable and Entity Framework entities

Time:11-23

Using Net 6 and Entity Framework I have the following entity:

public class Address {

  public Int32 Id { get; set; }
  public String CountryCode { get; set; }  
  public String Locality { get; set; }
  public Point Location { get; set; }

  public virtual Country Country { get; set; }
  public virtual ICollection<User> Users { get; set; } = new List<User>();  

}

With <Nullable>enable</Nullable> in project definition I am getting the warnings:

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

In Address properties:

CountryCode, Locality, Location and Country.

I see a few options to deal with this:

public String? CountryCode { get; set; } 

public String CountryCode { get; set; } = null!; 

I could also add a constructor but not all properties (for example, navigation properties) can be in the constructor.

What would be the best approach?

CodePudding user response:

Personally, I just put this line on the top of all my model files (POCO/JSON models, DbContext etc):

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.

Just put that line on top of the file, no need to restore it.

There is another enter image description here

You get something like this:

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    public TestContext(DbContextOptions options) : base(options)
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.

Delete the last line and cut the first line to the top of the file.

CodePudding user response:

I came across same thing few days back and actually nullable reference type is there in .net 5 too but manually we have to add that into .csproj and with .net 6 it is there by default.

I took following approach.

If I know that my property is non-nullable and when migration generate it should have nullable false then I put this way.

public string CountryCode { get; set;} = null!; // This indicate that this property will have value eventually. so no warning generate during compilation.

When I know property can contain null and also nullable = true in db or migration then

public string? CountryCode {get;set;}
  • Related