更改外键约束命名约定

Change foreign key constraint naming convention

我们有自己的外部对象命名约定,我需要更改自动生成的外键约束的命名约定。现在它看起来像:FK_dbo.City_dbo.CityType_City_CityTypeId 但我希望它被称为 City_FKC_CityType.

我找到了一个 similar question,它说您可以手动更改约束的名称。但是,这不适合我,因为我有很多表和外键约束。

我找到了一些关于 "Custom Code First Conventions" 的信息,我想知道我是否可以使用它来更改约束的名称,或者是否有任何方法可以实现它?

另一种变体是下载EF的源代码,进行更改并使用它,但以备不时之需。

附带说明一下,我还想更改主键的命名约定。

您可以实现自定义 sql 生成器 class 从 SqlServerMigrationSqlGenerator 派生自 System.Data.Entity.SqlServer 命名空间:

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

然后您需要使用 DbConfiguration:

DbContext 中注册您的生成器
public class CustomDbConfiguration : DbConfiguration
{
    public CustomDbConfiguration()
    {
        SetMigrationSqlGenerator(SqlProviderServices.ProviderInvariantName,
            () => new CustomSqlGenerator());
    }
}

DbConfigurationTypeAttribute

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

更新:如果您想更改主键名称,您需要覆盖以下 Generate 方法:

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