EF Core – Add a foreign key

In this article, I’ll show how to add a foreign key using EF Core. Then I’ll show how foreign keys affect inserts and deletes. How to add a foreign key A Show has one or more Episodes. In this section, I’ll show how to link these two tables together to enforce the 1-to-many relationship. In … Read more

System.InvalidOperationException: Serializer options cannot be changed once serialization or deserialization has occurred

Problem When using System.Text.Json, it’s a good idea to reuse JsonSerializerOptions objects. This leads to a massive 200x speedup in subsequent calls to the serializer. The downside is you can’t change properties on the options object after you’ve passed it in a Serialize()/Deserialize() call. You’ll get the exception: System.InvalidOperationException: Serializer options cannot be changed once … Read more

WinForms – Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Problem In a WinForms project, if you try to call Invoke/BeginInvoke before the window handle is created, you’ll get the following exception: System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created Because this exception happens while the form is initializing, it typically results in the form not … Read more

C# – Switch from using HttpWebRequest to HttpClient

There are many reasons to use HttpClient instead of HttpWebRequest. For one, the MSDN docs strongly recommends against using HttpWebRequest, and using HttpClient instead. That should be enough, but if you need a little more convincing, take a look at the Practical reasons to not use HttpWebRequest section below. In addition to explaining why not … Read more

C# – Explicitly compare bool? with true/false to avoid compile-time errors and runtime exceptions

You can’t use nullable bools (bool?) exactly like regular bools, because they aren’t the same thing. When you try to use them like regular bools, you run into compiler errors and runtime exceptions. Fortunately, there is a simple, concise way to treat nullable bools almost-like regular bools. You have to explicitly compare them with true/false. … Read more