SqlException: Cannot insert explicit value for identity column

When you have a table with an identity column, and you try to specify the value for identity column when inserting a record, you’ll get the following exception: Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table ‘Movies’ when IDENTITY_INSERT is set to OFF. This error means you have an identity column in … Read more

EF Core – How to add a computed column

To add a computed column in EF Core, override DbContext.OnModelCreating() and specify the computed column using ModelBuilder, like this: In this article, I’ll show a full example of adding a computed column and then show how to specify that the computed column should be persisted. Example of adding a computed column Let’s say we have … Read more

EF Core – How to create a composite primary key

A composite primary key is a primary key that contains more than one column. In EF Core, to create a primary key with one column, you would use the [Key] attribute. To create a composite primary key with multiple columns, you have to override DbContext.OnModelCreating() and then specify all of the columns included in the … Read more

EF Core – How to add indexes

In this article, I’ll show how to add indexes using EF Core. If you’re not sure about why you would need indexes, take a look at this article explaining how indexes greatly improve query performance. Add an index with a single column The simplest way to add an index is to by adding the [Index] … Read more

EF Core – Add a foreign key

In this article, I’ll show how to add a foreign key using EF Core. Then I’ll show how foreign keys affect inserts and deletes. How to add a foreign key A Show has one or more Episodes. In this section, I’ll show how to link these two tables together to enforce the 1-to-many relationship. In … Read more

EF Core – Database schema changes

Anytime you change the definition of the database – from renaming a column to creating a table – it’s referred to as a database schema change. With EF Core, you deal with database schema changes by using migrations. When you first create the database, you create a migration that contains the initial definition of the … Read more

EF Core – How to create a database and a table

In this article, I’ll show how to use EF Core to create a database with one table in it. At the end, I’ll show a standalone console app that inserts a record into this database. Note: I’ll be using SQL Server. I haven’t tried this with other database providers. Please leave a comment if you’re … Read more