Entity Framework Core Pitfalls - Getting a Single Record by Key
Introduction One more for the EF Core pitfalls series . EF Core offers essentially two ways to get a record with a known primary key: The native Find / FindAsync methods from DbContext or DbSet<T> A regular Where clause followed by one of First / FirstOrDefault or Single / SingleOrDefault , both from standard LINQ extensions , or FirstAsync / FirstOrDefaultAsync , SingleAsync / SingleOrDefaultAsync , the asynchronous alternatives from the EF Core LINQ extensions There are a few differences between these approaches, and also a couple limitations, which I'll cover here. I will use as example a blogging domain model, where a Blog has many Posts , each Post references its Blog , and a Post has many Comments . Like in other tips, this may or may not be a pitfall, but there is a possibility that we are not counting on this. Using Find/FindAsync Methods Find / FindAsync methods are great, because they allow us to retrieve a single entity wi...