Entity Framework primary key constraint

左心房为你撑大大i 提交于 2021-01-29 12:44:45

问题


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.


回答1:


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




回答2:


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;}



回答3:


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());


来源:https://stackoverflow.com/questions/29099685/entity-framework-primary-key-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!