Kevin O'Donovan
Kevin O'Donovan

Reputation: 1669

Nullable reference warning on navigation property in linq query

I have the following class (only relevant fields included) which is mapped to a database table:

public class Report {
  public int? LocationClassificationID { get; set; }
  public virtual Lookup? LocationClassification { get; set; }
}

The mapping is as follows

        e.HasOne(x => x.LocationClassification).WithMany().HasForeignKey(x => x.LocationClassificationID);

I'm writing a linq query as follows:

    Model.Reports
        .Select(x => new {
            Field=x.LocationClassification.Text

The compiler gives a possible null reference exception against LocationClassification in the query, but in this case the null dereference isn't an issue as linq handles this transparently. I can get rid of the warning by declaring the class property as follows:

  public virtual Lookup LocationClassification { get; set; } = null!;

but is this right? The documentation says to use null! when you know a property will never really be null, but in this case that property can be null, it just doesn't matter in the linq query, but could potentially give an exception if I reference that field in code.

What's the correct way to handle the above, keeping the null protection but without the warning in the linq query?

Upvotes: 0

Views: 1385

Answers (1)

Guru Stron
Guru Stron

Reputation: 141565

You can use the null forgiving operator which was designed for such cases in query itself:

Model.Reports
    .Select(x => new
    {
        Field = x.LocationClassification!.LocationClassificationID
        ...
    });

If you are doing it a lot and you don't like then your option with making property non-nullable is way to go (see the docs) but either way it's a trade-off you need to decide what is more relevant to your - compile time nullability checks or some extra code.

Also you as an option you can separate your database access layer and disable NRT just for it (either for whole project or using #nullable disable preprocessor directive for the files which have queries).

Upvotes: 1

Related Questions