Manu
Manu

Reputation: 1470

Change composite primary key to single field primary key with code first migration

I have this entity:

    public class GWDetail: Entity
{
    public int? GWNR { get; set; }
    public double? PRNR { get; set; }
    public double? GWO { get; set; }
    public double? GWU { get; set; }

}

mapped with a composite PK

        // Primary Key
        HasKey(t => new { t.PRNR, t.GWNR });

and want to change it to:

    public class GWDetail: Entity
{
    public int? GWNR { get; set; }
    public int? PRNR { get; set; }   // change from double to int !!
    public double? GWO { get; set; }
    public double? GWU { get; set; }

}

and

            // Primary Key
        HasKey(t => t.Id)

I have created the add-migration script and applied update-database but get:

Error Number:5074,State:1,Class:16 The object 'PK_dbo.GWDetail' is dependent on column 'PRNR'. ALTER TABLE ALTER COLUMN PRNR failed because one or more objects access this column.

GWDetail does not have any records yet. But there is a parent table that has a 1:n relationship via GWNR to it. The parent table has records.

Can someone help me with this? Thanks and regards, Manu

Upvotes: 0

Views: 832

Answers (1)

Manu
Manu

Reputation: 1470

I worked it out myself by changing the sequence of actions in the migration script.

This is the script created by EF:

        public override void Up()
    {
        AddColumn("dbo.GWDetails", "Id", c => c.Int(nullable: false, identity: true));
        AlterColumn("dbo.GWDetails", "PRNR", c => c.Int(nullable: false));
        AlterColumn("dbo.GWDetails", "GWNR1", c => c.Int());
        DropPrimaryKey("dbo.GWDetails", new[] { "PRNR", "GWNR1" });
        AddPrimaryKey("dbo.GWDetails", "Id");
    }

And here the script that I used to update-database:

        public override void Up()
    {
        DropPrimaryKey("dbo.GWDetails", new[] { "PRNR", "GWNR1" });
        AlterColumn("dbo.GWDetails", "PRNR", c => c.Int(nullable: false));
        AlterColumn("dbo.GWDetails", "GWNR1", c => c.Int());
        AddColumn("dbo.GWDetails", "Id", c => c.Int(nullable: false, identity: true));
        AddPrimaryKey("dbo.GWDetails", "Id");
    }

The critical action was:

DropPrimaryKey("dbo.GWDetails", new[] { "PRNR", "GWNR1" });

which I had to place into the first line of the script. I don't understand why EF would try to create the new key while the old one is still present. Regards, Manu

Upvotes: 0

Related Questions