Entity Framework Change Primary Key Type

c# entity-framework entity-framework-6

Question

I'm using EF 6.0 Code First, and I have this entity:

 public class TrainingRespect
 {
    [Key]
    public int RespectId { get; set; }

    public DateTime? DateWhenRespected { get; set; }

    #region

    public string UserId { get; set; }
    public User User { get; set; }

    public Guid TrainingId { get; set; }
    public Trening Training { get; set; }

    #endregion
 }

And I would like to change it's Primary Key (RespectId) from int to GUID / string / long.

What is easiest way of doing this ? Can I just change type and EF migrations will take care of everything or it should be done some other way ?

1
5
1/23/2015 10:44:20 AM

Accepted Answer

Ok to actually answer your question. Yes you can just change the data type and Migrations should take care of it.

However based off your comments you're having trouble applying this migration. This doesn't negate the above but I'll attempt to help using a bit of guesswork.

If you're using Sql Azure, you must have clustered indexes on all tables. EF6 should create clustered indexes even on string keys. There is a bug with alpha 3 though where it doesn't create a clustered key on the migrations table.

http://entityframework.codeplex.com/discussions/435723

See the above link for a description and a workaround.

If you're still having trouble, you can run the following command from the package console:

Update-Database -Script

This will produce a SQL Script instead of trying to update directly. You can look at this and see if any of the Create Table statements do not have a clustered index on them.

If, for some reason there aren't. You can explicitly modify your migration's CreateTable statement to make the primary key clustered.

CreateTable("MyTable", 
    c => new { 
        Id = c.String(nullable: false, maxLength: 128)
    })
.PrimaryKey(t => t.Id, null, true);

Also worth noting: Guids make terrible clustered indexes. If you're using GUID keys and have the option, don't cluster on them and have a second clustered index instead.

2
1/23/2015 11:44:20 AM

Popular Answer

Here one solution if you want to changing primary key data type in EF Core:

  • Drop the indexes and constraints
  • Rename Id to Old Id
  • Make new Id of the right datatype
  • Run an embedded sql statement to update the foreign keys
  • Drop old id
  • Create new indexes and constraints

Here is the full article: https://www.codeproject.com/Articles/1193009/Changing-primary-key-data-type-in-EF-Core



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow