Change foreign key constraint naming convention

前端 未结 1 1614
夕颜
夕颜 2020-12-03 17:56

We have our own external convention of naming objects and I need to change the naming convention for the auto generated foreign key constraints. Now it looks like: FK_

相关标签:
1条回答
  • 2020-12-03 18:29

    You can implement a custom sql generator class derived from SqlServerMigrationSqlGenerator from System.Data.Entity.SqlServer namespace:

    public class CustomSqlGenerator : SqlServerMigrationSqlGenerator
    {
        protected override void Generate(AddForeignKeyOperation addForeignKeyOperation)
        {
            addForeignKeyOperation.Name = getFkName(addForeignKeyOperation.PrincipalTable,
                addForeignKeyOperation.DependentTable, addForeignKeyOperation.DependentColumns.ToArray());
            base.Generate(addForeignKeyOperation);
        }
    
        protected override void Generate(DropForeignKeyOperation dropForeignKeyOperation)
        {
            dropForeignKeyOperation.Name = getFkName(dropForeignKeyOperation.PrincipalTable,
                dropForeignKeyOperation.DependentTable, dropForeignKeyOperation.DependentColumns.ToArray());
            base.Generate(dropForeignKeyOperation);
        }
    
        private static string getFkName(string primaryKeyTable, string foreignKeyTable, params string[] foreignTableFields)
        {
            // Return any format you need
        }
    }
    

    Then you need to register your generator in DbContext using DbConfiguration:

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

    And DbConfigurationTypeAttribute:

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

    UPDATE: If you want to change a primary key name, you need to override following Generate methods:

    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);
    }
    
    0 讨论(0)
提交回复
热议问题