Entity Framework Change Primary Key Type

c# entity-framework entity-framework-6

Question

With EF 6.0 Code First, I have the following 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 want to convert the Primary Key (RespectId) from an int to a GUID, string, or long.

What's the simplest approach to accomplish this? Can I simply alter the type and have EF migrations handle everything, or is there another way to go about this?

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

Accepted Answer

Okay, let me truly respond to your query. You only need to alter the data type, and Migrations should handle the rest.

Based on your comments, it appears that you are experiencing problems implementing this migration. This doesn't change the aforementioned, but I'll try to help by making some educated guesses.

All of your tables must have clustered indexes if you're using SQL Azure. Even with string keys, EF6 should build clustered indexes. Nevertheless, there is an issue in alpha 3 that prevents the creation of a clustered key on the migrations table.

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

For a description and a workaround, click the link up above.

Run the following command from the package console if you're still having issues:

Update-Database -Script

Instead of attempting to update directly, this will create a SQL Script. If any of the Create Table statements don't have a clustered index on them, you can check this and see.

If there aren't, for whatever reason. To make the primary key clustered, you can specifically change the CreateTable statement in your migration.

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

Noteworthy as well: Guids produce subpar clustered indexes.. If you have the choice and are utilizing GUID keys, avoid clustering on them in favor of a second clustered index.

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

Popular Answer

ZZZ_tmp


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