Category: Entity Framework

EF Core - empty inverse property list despite using Include and ThenInclude

Yesterday, I created a new project to play around with Blazor and .NET 5. However, my fun was cut short when EF Core refused to fetch dependent child properties. This is despite using eager loading with Include. Clean projects, unit tests, nullable reference types, init properties, the code was super simple with just 2 classes

Continue Reading

EF Core - using letters instead numbers for enums in the database

Sometimes, I actually prefer to store letters for rather than integers in the database. Yes, it can be less performant (as you do need to implement a custom converter), but can make the database a lot easier to read. Consider the example below that TradeDirection. It might be more preferable to see B and S

Continue Reading

GUID as an Alternative Key in EF Core

EF Core supports GUIDs as IDs. However, I've run into a couple of instances where it is/not not supported by 3rd party libraries (like https://github.com/artiomchi/FlexLabs.Upsert). I also prefer to use numerical IDs in the database as they take less space and are far more convenient to work with. However, exposing sequential numeric IDs can lead

Continue Reading

Using LocalDB for Integration/Unit Tests

Long did I hold this perception that integration tests are hard. With EF core, they are actually really easy. Instead of using SQL Sever, we can substitute with LocalDB. Run this before running the tests and you'll have your db setup. After calling EnsureCreated you can add things into the database.

Continue Reading

The ALTER TABLE statement conflicted with the FOREIGN KEY constrain

I've been trying to apply a new migration and I was getting the following error: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Parent_dbo.Childs_ChildId". The conflict occurred in database "parents_db", table "dbo.Childs", column 'ChildId'. In my case, the table contained data. Therefore, either you have to assign a default value, set it as

Continue Reading

ASP.NET Automatic Migrations

Understanding migrations can be a bit tricky. Hopefully, this article will resolve at least some of the questions you might have. First things first - What are migrations? Well... If you built your website using first code approach every time you change your model you need in order to keep the database in sync. There

Continue Reading

Setting default value for property in EF Code First

There few ways in which one can do it. The simplest way is via data annotations:

Continue Reading

Using InverseProperty and ForeignKey Attributes

InverseProperty and ForeignKey are (arguably) the most commonly used attribues in Entity Framework when developing in code-first approach. They help greatly simply the job of managing our models. Foreign Key In order to introduce foreign key to our code we need to specify to what objects it maps to. So there are two things that

Continue Reading