Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix optional navigation sample in NRT page #4352

Merged
merged 1 commit into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ Another strategy is to use non-nullable auto-properties, but to initialize them

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:

[!code-csharp[Main](../../../samples/core/Miscellaneous/NullableReferenceTypes/Program.cs?name=Navigating)]
```csharp
var order = context.Orders
.Where(o => o.OptionalInfo!.SomeProperty == "foo")
.ToList();
```

A similar issue occurs when including multiple levels of relationships across optional navigations:

Expand Down
4 changes: 0 additions & 4 deletions samples/core/Miscellaneous/NullableReferenceTypes/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,6 @@ private static void Main(string[] args)
// Console.WriteLine(order.ShippingAddress.City);
// The following would be a programming bug: we forgot to include Product above; will throw NullReferenceException. It would throw NullReferenceException.
// Console.WriteLine(order.Product.Name);

#region Navigating
Console.WriteLine(order.OptionalInfo!.ExtraAdditionalInfo!.SomeExtraAdditionalInfo);
#endregion
}
}
}
Expand Down