You'd find a lot of different answers on this question
But in this particular case, I would ask myself the question: who generates instances of this class?
1a
If you are 100% relying on EF Core to generate instances of this class for you by querying the database, and you are 100% sure that you ALWAYS use the proper Include()
, I would safely set the Author
field to null!
, which means it assigns the default value null
on construction and automatically suppresses the nullability error.
public class Article
{
public int Id { get; set; }
public User Author { get; set; } = null!;
public int AuthorId { get; set; }
}
1b
You could also use the above solution with a private constructor to protect that no-one else but EF Core will generate instances of this class.
public class Article
{
private Article()
{
Author = null!;
}
public int Id { get; set; }
public User Author { get; set; }
public int AuthorId { get; set; }
}
2
If you generate instances of this class in any other parts of your code, you would need a constructor to ensure that Author
is never null after construction.
public class Article
{
public Article()
{
Author = new User();
}
public int Id { get; set; }
public User Author { get; set; }
public int AuthorId { get; set; }
}
3
If you do not allow a default User
object, it would make sense to expect a null
value for Author
but mark it Required
to ensure that it will never be null
when written to database.
public class Article
{
public int Id { get; set; }
[Required]
public User? Author { get; set; }
public int AuthorId { get; set; }
}