I have a .NET 6 project with nullable reference types enabled (<Nullable>enable</Nullable>
). I have this EF entity:
public class PostFile {
public Int32 UserId { get; set; }
public Int32 PostId { get; set; }
public virtual User? User { get; set; }
public virtual Post? Post { get; set; }
}
I added ?
above to prevent this nullable warning:
Non-nullable property '...' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
Now, I have this Entity Framework 6 LINQ query:
var postFiles = context.postFiles.Where(x => x.User.Id == request.UserId);
... but I get the following warning:
Dereference of a possibly null reference.
... on this part of my query:
x.User.Id == ...
How can I fix this warning?
You should mark navigation entities as nullable. You should not have lazy loading enabled, and therefore navigation properties can be returned as null
from queries. Even if they are required in the database, your code doesn't have to load them.
In your query expressions, you can be certain that Entity Framework isn't going to execute them clientside, but parse an SQL query out of them.
Therefore:
.Where(x => x.User!.Id == request.UserId)
You can tell the compiler with User!
that you know it won't be null there. Unless you enable clientside evaluation, but you shouldn't, and if you do, you'll need a null check there anyway.
As for usage of PostFile.User
, as in:
var postFile = dbContext.PostFiles.FirstOrDefault(p => p....) ?? throw ...;
var user = postFile.User;
There it can be null
if you didn't Include(p => p.User)
and don't have lazy loading enabled, so user
would need a null check before usage.
If you do use lazy loading, you can disable the warning:
#pragma warning disable CS8618 // EF initializes these properties through lazy loading
public virtual User User { get; set; }
#pragma warning restore CS8618
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With