Search code examples
c#sql-serverentity-framework-6

How to alter datatypes of primary and foreign keys using EF migration?


I have to change the datatypes from int to bigint on all of the primary and foreign keys that are used in an already existing database / tables.

To work around the following error...

Msg 5074, Level 16, State 8, Line 1
The object 'Primary Key Constraint Name' is dependent on column 'Primary Key Column Name'.
ALTER TABLE ALTER COLUMN Column Name failed because one or more objects access this column.

I first have to drop the constraint and then re-create it later on. This is how I do it using SSMS:

alter table Meta.Playground
drop constraint Pk_Playground
go

alter table Meta.Playground
alter column id bigint not null
go

alter table Meta.Playground
add constraint Pk_Playground primary key (id)
go

But what would be the best way to do this using entity-framework's Up() and Down() methods?

I don't know how I can retrieve the key and constraint names from within those methods.

By using SQL I would retrieve them as follows:

select COLUMN_NAME, CONSTRAINT_NAME 
into #result
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
where TABLE_NAME = @table and TABLE_SCHEMA = @schema

Solution

  • I realized that the way I am trying to solve this problem is ways to complicated.

    Adding an additional migration step solves my problem in an astonishing easy way. So no need for an additional SQL script. Entity framework is fully able to migrate the primary and foreign keys (at least version 6.1.3 which I am using).

    This is what the code looks like after calling Add-Migration with the appropriate parameters.

    public override void Up()
    {
        DropForeignKey(...)
        // ...
        DropIndex(...) 
        // ... 
        DropPrimaryKey(...)
        // ...
        AlterColumn(...)
        // ...
        AddPrimaryKey(...)
        // ...
        CreateIndex(...)
        // ...
        AddForeignKey) 
        // ...
    }