How to Specify Primary Key Name in EF-Code-First
If you want to specify the column name and override the property name, you can try the following:
Using Annotations
public class Job
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("CustomIdName")]
public Guid uuid { get; set; }
public int active { get; set; }
}
Using Code First
protected override void OnModelCreating(DbModelBuilder mb)
{
base.OnModelCreating(mb);
mb.Entity<Job>()
.HasKey(i => i.uuid);
mb.Entity<Job>()
.Property(i => i.uuid)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnName("CustomIdName");
}
Inside Migration Configuration
public partial class ChangePrimaryKey : DbMigration
{
public override void Up()
{
Sql(@"exec sp_rename 'SchemaName.TableName.IndexName', 'New_IndexName', 'INDEX'");
}
public override void Down()
{
Sql(@"exec sp_rename 'SchemaName.TableName.New_IndexName', 'Old_IndexName', 'INDEX'");
}
}
You can use the Key attribute to specify the parts of the primary key. So your Job class might be
public class Job
{
[Key]
public Guid uuid{ get; set; }
public int active{ get; set; }
}
The data annotation attributes are defined in the System.ComponentModel.DataAnnotations namespace
If I understand, you are asking how to change the name of the primary key column used by Entity Framework. The following addition to your HasKey statement should take care of this:
modelBuilder.Entity<Job>().Property(j => j.uuid).HasColumnName("pk_Jobs")