Change PrimaryKey EntityFramework

0

How to change a primary key using EntityFramework?

I have a table with simple PK and need to change this PK through EntityFramework.

    
asked by anonymous 27.09.2017 / 13:33

1 answer

0
  

The solution below may work, as I have not tested it, I ask you to do it,   if it does not work, please comment below so I can   remove this response.

First step, you should change all your FKs that refer to the key you want to change.

Because EF assumes that the PK will never be changed, you will not be able to do this for Migrations, so if you are using SQL Server, you can run a script like this.

alter table Detail 
  drop constraint FK_Master_Detail

alter table Detail 
  add constraint FK_Master_Detail 
      foreign key (MasterID) 
      references Cars(MasterID) 
      --on delete cascade 
      on update cascade

The second thing to do is to install the following package:

Z.EntityFramework.Plus.EF6 p>

Then run the following command ...

ctx.Entities
    .Where(x => x.EntityID == oldEntityID)
    .Update(x => new Entity() { EntityID = newEntityID });

Just to remind you, I do not give you any guarantee that the code above will work. but you have one more option, which would be using Raw Sql, so I advise you to use Dapper .

await ctx.Database.Connection
    .QueryAsync("UPDATE Entities SET EntityID = @newEntityID WHERE EntityID = @oldEntityID", 
        new { newEntityID = newEntityID, oldEntityID = oldEntityID }
    );

Finally, just a suggestion, do not use natural keys, give preference to a substitute key. s you can declare your tables as follows:

CREATE TABLE dbo.Entities (
    EntityID uniqueidentifier NOT NULL,
    NaturalID int NOT NULL --IDENTITY (1, 1)
) ON [PRIMARY]

ALTER TABLE dbo.Entities ADD CONSTRAINT
    PK_Entities PRIMARY KEY NONCLUSTERED (EntityID) 
    WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

CREATE UNIQUE CLUSTERED INDEX IXCU_Entities 
    ON dbo.Entities (NaturalID) 
    WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

And remember, never show your replacement keys to the end user, he does not need and should not know of their existence.

    
27.09.2017 / 13:58