Skip to content

Commit 6b9686b

Browse files
authored
Tweak NRT guidance (#2778)
Fixes #2529
1 parent 662d161 commit 6b9686b

File tree

5 files changed

+49
-11
lines changed

5 files changed

+49
-11
lines changed

entity-framework/core/miscellaneous/nullable-reference-types.md

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ uid: core/miscellaneous/nullable-reference-types
77
---
88
# Working with Nullable Reference Types
99

10-
C# 8 introduced a new feature called [nullable reference types](/dotnet/csharp/tutorials/nullable-reference-types), allowing reference types to be annotated, indicating whether it is valid for them to contain null or not. If you are new to this feature, it is recommended that make yourself familiar with it by reading the C# docs.
10+
C# 8 introduced a new feature called [nullable reference types (NRT)](/dotnet/csharp/tutorials/nullable-reference-types), allowing reference types to be annotated, indicating whether it is valid for them to contain null or not. If you are new to this feature, it is recommended that make yourself familiar with it by reading the C# docs.
1111

1212
This page introduces EF Core's support for nullable reference types, and describes best practices for working with them.
1313

@@ -18,17 +18,17 @@ The main documentation on required and optional properties and their interaction
1818
> [!NOTE]
1919
> Exercise caution when enabling nullable reference types on an existing project: reference type properties which were previously configured as optional will now be configured as required, unless they are explicitly annotated to be nullable. When managing a relational database schema, this may cause migrations to be generated which alter the database column's nullability.
2020
21-
## DbContext and DbSet
21+
## Non-nullable properties and initialization
2222

23-
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. This can be fixed as follows:
23+
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 following, common way of writing entity types cannot be used:
2424

25-
[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs?name=Context&highlight=3-4)]
25+
[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/CustomerWithWarning.cs?name=CustomerWithWarning&highlight=4-5)]
2626

27-
Another strategy is to use non-nullable auto-properties, but to initialize them to null, using the null-forgiving operator (!) to silence the compiler warning. The DbContext constructor ensures that all DbSet properties will get initialized, and null will never be observed on them.
27+
[Constructor binding](xref:core/modeling/constructors) is a useful technique to ensure that your non-nullable properties are initialized:
2828

29-
## Non-nullable properties and initialization
29+
[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/CustomerWithConstructorBinding.cs?name=CustomerWithConstructorBinding&highlight=6-9)]
3030

31-
Compiler warnings for uninitialized non-nullable reference types are also a problem for regular properties on your entity types. In our example above, we avoided these warnings by using [constructor binding](xref:core/modeling/constructors), a feature which works perfectly with non-nullable properties, ensuring they are always initialized. However, in some scenarios constructor binding isn't an option: navigation properties, for example, cannot be initialized in this way.
31+
Unfortunately, in some scenarios constructor binding isn't an option; navigation properties, for example, cannot be initialized in this way.
3232

3333
Required navigation properties present an additional difficulty: although a dependent will always exist for a given principal, it may or may not be loaded by a particular query, depending on the needs at that point in the program ([see the different patterns for loading data](xref:core/querying/related-data)). At the same time, it is undesirable to make these properties nullable, since that would force all access to them to check for null, even if they are required.
3434

@@ -47,6 +47,14 @@ An actual null value will never be observed except as a result of a programming
4747
> [!NOTE]
4848
> Collection navigations, which contain references to multiple related entities, should always be non-nullable. An empty collection means that no related entities exist, but the list itself should never be null.
4949
50+
## DbContext and DbSet
51+
52+
The common practice of having uninitialized DbSet properties on context types is also problematic, as the compiler will now emit warnings for them. This can be fixed as follows:
53+
54+
[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/NullableReferenceTypesContext.cs?name=Context&highlight=3-4)]
55+
56+
Another strategy is to use non-nullable auto-properties, but to initialize them to null, using the null-forgiving operator (!) to silence the compiler warning. The DbContext base constructor ensures that all DbSet properties will get initialized, and null will never be observed on them.
57+
5058
## Navigating and including nullable relationships
5159

5260
When dealing with optional relationships, it's possible to encounter compiler warnings where an actual null reference exception would be impossible. When translating and executing your LINQ queries, EF Core guarantees that if an optional related entity does not exist, any navigation to it will simply be ignored, rather than throwing. However, the compiler is unaware of this EF Core guarantee, and produces warnings as if the LINQ query were executed in memory, with LINQ to Objects. As a result, it is necessary to use the null-forgiving operator (!) to inform the compiler that an actual null value isn't possible:

entity-framework/core/modeling/entity-properties.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ In the following example, configuring the `Score` property to have precision 14
9191

9292
#### [Data Annotations](#tab/data-annotations)
9393

94-
Currently not possible to use data annotations to configure.
94+
Precision and scale cannot currently be configured via data annotations.
9595

9696
#### [Fluent API](#tab/fluent-api)
9797

@@ -110,18 +110,18 @@ A property is considered optional if it is valid for it to contain `null`. If `n
110110

111111
By convention, a property whose .NET type can contain null will be configured as optional, whereas properties whose .NET type cannot contain null will be configured as required. For example, all properties with .NET value types (`int`, `decimal`, `bool`, etc.) are configured as required, and all properties with nullable .NET value types (`int?`, `decimal?`, `bool?`, etc.) are configured as optional.
112112

113-
C# 8 introduced a new feature called [nullable reference types](/dotnet/csharp/tutorials/nullable-reference-types), which allows reference types to be annotated, indicating whether it is valid for them to contain null or not. This feature is disabled by default, and if enabled, it modifies EF Core's behavior in the following way:
113+
C# 8 introduced a new feature called [nullable reference types (NRT)](/dotnet/csharp/tutorials/nullable-reference-types), which allows reference types to be annotated, indicating whether it is valid for them to contain null or not. This feature is disabled by default, and affects EF Core's behavior in the following way:
114114

115115
* If nullable reference types are disabled (the default), all properties with .NET reference types are configured as optional by convention (for example, `string`).
116116
* If nullable reference types are enabled, properties will be configured based on the C# nullability of their .NET type: `string?` will be configured as optional, but `string` will be configured as required.
117117

118118
The following example shows an entity type with required and optional properties, with the nullable reference feature disabled (the default) and enabled:
119119

120-
#### [Without nullable reference types (default)](#tab/without-nrt)
120+
#### [Without NRT (default)](#tab/without-nrt)
121121

122122
[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/CustomerWithoutNullableReferenceTypes.cs?name=Customer&highlight=4-8)]
123123

124-
#### [With nullable reference types](#tab/with-nrt)
124+
#### [With NRT](#tab/with-nrt)
125125

126126
[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/Customer.cs?name=Customer&highlight=4-6)]
127127

samples/core/Miscellaneous/NullableReferenceTypes/Customer.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ public class Customer
88
public string LastName { get; set; } // Required by convention
99
public string? MiddleName { get; set; } // Optional by convention
1010

11+
// Note the following use of constructor binding, which avoids compiled warnings
12+
// for uninitialized non-nullable properties.
1113
public Customer(string firstName, string lastName, string? middleName = null)
1214
{
1315
FirstName = firstName;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
namespace NullableReferenceTypes
2+
{
3+
#region CustomerWithConstructorBinding
4+
public class CustomerWithConstructorBinding
5+
{
6+
public int Id { get; set; }
7+
public string Name { get; set; }
8+
9+
public CustomerWithConstructorBinding(string name)
10+
{
11+
Name = name;
12+
}
13+
}
14+
#endregion
15+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#pragma warning disable CS8618
2+
3+
namespace NullableReferenceTypes
4+
{
5+
#region CustomerWithWarning
6+
public class CustomerWithWarning
7+
{
8+
public int Id { get; set; }
9+
// Generates CS8618, uninitialized non-nullable property:
10+
public string Name { get; set; }
11+
}
12+
#endregion
13+
}

0 commit comments

Comments
 (0)