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