From db7df54678a225da9ebb85371be59263b46068c0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 20 Jul 2020 19:28:45 +0300 Subject: [PATCH] Improve nullability guidance for DbSets (#2520) See https://github.com/dotnet/efcore/issues/21608 --- .../core/miscellaneous/nullable-reference-types.md | 2 +- .../NullableReferenceTypes/NullableReferenceTypesContext.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/entity-framework/core/miscellaneous/nullable-reference-types.md b/entity-framework/core/miscellaneous/nullable-reference-types.md index 6bb152d68f..63488daf64 100644 --- a/entity-framework/core/miscellaneous/nullable-reference-types.md +++ b/entity-framework/core/miscellaneous/nullable-reference-types.md @@ -20,7 +20,7 @@ The main documentation on required and optional properties and their interaction ## DbContext and DbSet -When nullable reference types are enabled, the C# compiler emits warnings for any uninitialized non-nullable property, as these would contain null. As a result, the common practice of defining a non-nullable `DbSet` on a context will now generate a warning. However, EF Core always initializes all `DbSet` properties on DbContext-derived types, so they are guaranteed to never be null, even if the compiler is unaware of this. Therefore, it is recommended to keep your `DbSet` properties non-nullable - allowing you to access them without null checks - and to silence the compiler warnings by explicitly setting them to null with the help of the null-forgiving operator (!): +When nullable reference types are enabled, the C# compiler emits warnings for any uninitialized non-nullable property, as these would contain null. As a result, the common practice of having uninitialized DbSet properties on a context type will now generate a warning. To fix this, make your DbSet properties read-only and initialize them as follows: [!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs?name=Context&highlight=3-4)] diff --git a/samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs b/samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs index 71e6da1bc1..880dd015fd 100644 --- a/samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs +++ b/samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs @@ -5,8 +5,8 @@ namespace NullableReferenceTypes #region Context public class NullableReferenceTypesContext : DbContext { - public DbSet Customers { get; set; } = null!; - public DbSet Orders { get; set; } = null!; + public DbSet Customers => Set(); + public DbSet Orders => Set(); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder