liveBook · Manning

Key attribute

As explained in Building Web APIs with ASP.NET Core

The Key data annotation attribute is a .NET model annotation that marks a property as an entity's primary key.

The [Key] data annotation marks a property as an entity’s primary key. In the BoardGame API, placing it on BoardGame.Id tells EF Core to create Id as the primary-key column. section 5.3.6

That mapping can also produce an identity column in the generated migration. SQL Server then assigns and increments IDs automatically, so manually inserting imported IDs fails while IDENTITY_INSERT is OFF. section 5.3.6

Resolve the conflict according to whether existing identifiers matter:

  • Remove the BoardGame.Id assignment and let the database generate new IDs. section 5.3.6
  • Preserve imported IDs by enabling IDENTITY_INSERT before saving and disabling it afterward inside the transaction. section 5.3.6

Board-game data seeding

A PUT /Seed request fails with a 500 response when CSV identifiers are assigned to BoardGame.Id. Preserving those identifiers requires temporarily enabling IDENTITY_INSERT during SaveChangesAsync. section 5.3.6

Microsoft.EntityFrameworkCore.DbUpdateException: 
An error occurred while saving the entity changes.
See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904):
Cannot insert explicit value for identity column
in table 'BoardGames' when IDENTITY_INSERT is set to OFF.

Inspect the database error produced when explicit values are inserted into an identity column with IDENTITY_INSERT disabled. section 5.3.6

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains primary-key mapping and identity-column consequences, then stops at seed-operation remedies.
Examples
Uses BoardGame.Id, CSV imports, the PUT /Seed endpoint, and an IDENTITY_INSERT transaction.
What it assumes
Assumes familiarity with EF Core entities, migrations, SQL Server, and database seeding.
What you can do after
Diagnose explicit-identifier seeding failures and choose between generated IDs and temporary IDENTITY_INSERT.
How it connects
Connects data annotations with EF Core, primary keys, migrations, identity columns, SQL Server, and database seeding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.