更改外键约束命名约定

时间:2015-07-21 09:14:51

标签: c# entity-framework naming-conventions code-first

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

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

我找到了一些关于"自定义代码优先约定的信息"我想知道我是否可以使用此更改约束的名称,或者是否有任何方法来实现它?

另一个变体是下载EF的源代码,进行更改并使用它,但这是紧急情况。

作为旁注,我还想更改主键的命名约定。

1 个答案:

答案 0 :(得分:9)

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

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

然后,您需要使用DbContext

DbConfiguration中注册您的生成器
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);
}