0

I am using Entity Framework 6.0 with Microsoft SQL Server. By default, the primary key it generates for a table is named like PK_dbo.TableName, where TableName is in a plural form, even though the actual name of the table is in a singular form.

For example, I have a table named dbo.Employee. Yet the primary key denoted by EF 6 is PK_dbo.Employees.

Is there any way to change the primary key to something like PK_TableName where the TableName is in a singular form?

Update: Thanks for the replies. I didn't mean to rename to column name of the primary key. What I like is to rename the key constraints in the generated database, which is requested by a database person in our team. Sorry that I didn't make it clear in my first post. I did see some discussions in this post: Entity Framework 4.1: Name constraints. However no simple solutions had been identified yet.

Community
  • 1
  • 1
Hao Jiang
  • 41
  • 4
  • 1
    possible duplicate of [How to Specify Primary Key Name in EF-Code-First](http://stackoverflow.com/questions/13607512/how-to-specify-primary-key-name-in-ef-code-first) – Richard Mar 17 '15 at 13:02
  • Specifically: look at this answer: http://stackoverflow.com/a/13610005/67392 – Richard Mar 17 '15 at 13:03

3 Answers3

2

You can do it like this:

public class PKNameGenerator : SqlServerMigrationSqlGenerator {
        static readonly string PREFIX = "PK";
        protected override void Generate(CreateTableOperation createTableOperation) {
            createTableOperation.PrimaryKey.Name = GetPkName(createTableOperation.Name);
            base.Generate(createTableOperation);
        }

        protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation) {
            addPrimaryKeyOperation.Name = GetPkName(addPrimaryKeyOperation.Table);
            base.Generate(addPrimaryKeyOperation);
        }

        protected override void Generate(DropPrimaryKeyOperation dropPrimaryKeyOperation) {
            dropPrimaryKeyOperation.Name = GetPkName(dropPrimaryKeyOperation.Table);
            base.Generate(dropPrimaryKeyOperation);
        }

        // Prefix + Table name without schema
        string GetPkName(string tableName) {
            return PREFIX + tableName.Substring(tableName.IndexOf('.')+1);
        }
    }

And then you need to register it like that:

public class DataContextConfiguration : DbConfiguration {
            public DataContextConfiguration() {      
                SetMigrationSqlGenerator(SqlProviderServices.ProviderInvariantName, () => new PKNameGenerator());
            }
        }

Make sure to place the above class in the same assembly as a class derived from DbContext or use the DbConfigurationTypeAttribute

[DbConfigurationType(typeof(CustomDbConfiguration))]
public class YourEntities : DbContext

Source: https://stackoverflow.com/a/31553476/3111429

More info: https://entityframework.codeplex.com/wikipage?title=Code%20First%20Annotations Section SQL Generation

Using EF Core you can do it like this:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasKey(b => b.BlogId)
            .HasName("PrimaryKey_BlogId");
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Source: http://ef.readthedocs.io/en/latest/modeling/relational/primary-keys.html#fluent-api

Community
  • 1
  • 1
Kautsky Lozano
  • 722
  • 12
  • 21
0

You could set the name of your db-field explicitly, although I'm not sure if that is what you're looking for.

[Key]
[Column("PK_Employee")]
public int EmployeeId {get; set;}
Manuel Schweigert
  • 4,884
  • 4
  • 20
  • 32
0

Fluent API is clean, so more cleaner this way with separate configuration file

public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(x => x.EmployeeId);
    }
}

And OnModelCreating you can add this configuration file

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new EmployeeConfiguration());
Sandip Bantawa
  • 2,822
  • 4
  • 31
  • 47