Kevin O'Donovan
Kevin O'Donovan

Reputation: 1669

Stop nullability warnings from entity framework queries that include nullable navigation properties

Consider an entity framework core model with the following two entities:

public class RiskAssessment {
  public string Title { get; set; } = string.Empty;
  public Guid? ActivityID { get; set; }

  public Activity? Activity { get; set; }
}

public class Activity {
  public Guid ID { get; set; }
  public string Name { get; set; } = null!;
}

Activity is a nullable navigation property.

I can write a query like the following using these entities:

return await session.RiskAssessments
    .Select(x => new {x.Title, x.Activity.Name}).ToListAsync();

This query runs without problems and if Activity is null it returns null for the second field. However Visual Studio highlights x.Activity with a null reference warning. Can anyone recommend a way to avoid this warning? I can surround the query with a pragma to disable the warning, but that's quite ugly. I could disable warnings for the entire class, but the class may contain other methods where I'd like to be warned of potential null references. Is there a recommended way to approach this that I've missed?

EDIT: I hadn't specified this was for entity framework core in the question - added that now. I should also point out an additional option that works, but it's still quite nasty as it adds code complexity:

return await session.RiskAssessments
    .Select(x => new {x.Title, x.Activity==null?null:x.Activity.Name}).ToListAsync();

In its favour the extra code is ignored by entity framework when generating the underlying SQL query

Upvotes: 0

Views: 440

Answers (1)

Kevin O'Donovan
Kevin O'Donovan

Reputation: 1669

Guess this is a "Kernighan's Teddy" moment. As soon as I edited the question in response to Poul's suggestion the answer leapt out at me:

return await session.RiskAssessments
    .Select(x => new {x.Title, x.Activity!.Name}).ToListAsync();

The null forgiving operation is supported in EF Core queries. Hopefully this will point someone else in the right direction!

Upvotes: 1

Related Questions