Search code examples
.netsql-serverentity-frameworkentity-framework-6

Primary key identifier difference between Entity Framework and SQL Server


I am working on a DB-first environment with a .NET application.

I realized when I create migration files, Entity Framework does not pick up the correct primary key name from SQL Server when it needs to drop a primary key.

This is what the migration file generates to drop the primary key:

DropPrimaryKey("dbo.TableName");

But in SQL Server, the PK constraint is like this:

[PK__TableName__48AFA797B7F88EC3]

I have two questions:

  • Why does the PK constraint have these randomly generated numbers in the name?
  • Why can Entity Framework not detect that name and create a migration file according to the current schema?

When I run the migration file contains DropPrimaryKey("dbo.TableName"); it doesn't work and I get this error:

'PK_dbo.TableName' is not a constraint.
Could not drop constraint. See previous errors.


Solution

  • Why PK has these randomly generated numbers in the name?

    If you don't name the constraint, SQL Server will generate a name for it.

    When I run the migration file . . .

    Why are you even generating migrations? In a database-first workflow you apply schema changes directly to the database and then re-scaffold or adjust the EF model to match. Migrations are only used in a code-first workflow.