.NET and EF Core Keyless Entities
.NET and EF Core Keyless Entities

How to Define Keyless Entities in .NET EF Core

Sometimes, we may need to declare EF core models which do not have primary keys. In this article, let’s understand why such entities would be required and how to define them.

What is it ?

When any EF core model is defined, by default, EF core marks a property as primary key. A property can be declared to be a primary key by decorating it with [Key] attribute or via Fluent API HasKey.

If not explicitly specified, EF core checks if there is a property with name “Id” or {EntityName}Id. If there is such property, then it is by default marked as primary key for the entity.

If there is no such property, then EF core throws an error:

The entity type ‘{EntityName}’ requires a primary key to be defined. If you intended to use a keyless entity type, call ‘HasNoKey’ in ‘OnModelCreating’.

The error is asking to define a primary key on the model. But what if we do not want to ? How to achieve that ? Well the answer is in the error message itself. But before looking at syntax, let’s first see where keyless entities would be required.

Why would it be required ?

Keyless entities may be required if database schema contains a table or a view without any primary key. In such cases, this table or view can be mapped to a keyless entity. Sometimes keyless entities can also be used to map results from a Raw SQL.

How to define it ?

There are two ways to define a keyless entity

  • Use data annotation [Keyless]. Annotate a model with this attribute
  • OR use fluent API .HasNoKey to define the keyless entity

When an entity is defined as keyless entity, it cannot contain a primary key. So it can never be a principal entity as it does not have a key. Also, keyless entities are not tracked by DbContext.

Below code snippet shows how to use fluent API to mark an entity “Student” as keyless. The code also maps this entity to a view.

I hope you find this information helpful. Let me know your thoughts.

Leave a ReplyCancel reply

This Post Has One Comment