How to use C# 9 records with EF Core?

From official document

Entity Framework Core depends on reference equality to ensure that it
uses only one instance of an entity type for what is conceptually one
entity. For this reason, record types aren’t appropriate for use as
entity types in Entity Framework Core.

This could confuse some people. Pay close attention to the documentation. records might not be suited for entities, but they are just fine for owned types for example, like value objects (in DDD-terms), because such values don’t have a conceptual unique identity.

For example, if an Address entity, modeled as a class, owns a City value object, modeled as a record, EF would usually map City as columns inside Address like this: City_Name, City_Code, etc. (ie. record name joined with an underscore and the property name).

Notice that City has no Id, because we’re not tracking unique cities here, just names and codes and whatever other information you could add to a City.

Whatever you do, don’t add Ids to records and try to map them manually, because two records with the same Id don’t necessarily mean the same conceptual entity to EF, probably because EF compares object instances by reference (records are ref types) and doesn’t use the standard equality comparer which is different for records than for standard objects (needs confirmation).

I myself don’t know how EF’s works on the inside very well to talk with more certainty, but I trust the docs and you should probably trust them too, unless you want to read the source code.

Leave a Comment