EF Code First - setting or imposing foreign key link names

I read a lot of posts on how to specify a foreign key name in a relationship, there are no problems. However, I would like to know if there is a way to change what primary keys and relationships are called?

For example, you have a User table with UserId as the primary key. The primary key is called PK_User_1788CC4C07020F21 (or something like that) by generating the first EF code database. Or you have a link from your User table to your UserVersion table and it is called UserVersion_User EF. I would like the primary key to be called PK_User and the external link to be called FK_UserVersion_User .

Is there any way to do this? Do some conventions redefine or may actually indicate text?

Thank.

Update: Based on the answer and the link below, I did the following in the Seed method. This is a kind of brute force, but I believe that it can be improved, especially if you create configuration files for the configuration file, etc. With a generator. The same could be done for foreign key link names.

    protected override void Seed(TodoDataContext context)
    {
        FixIndexes(context, "User");
        FixIndexes(context, "UserStats");
        FixIndexes(context, "UserRole");
        FixIndexes(context, "UserVersion");
        FixIndexes(context, "UserUserRoleVersion");
    }

    private void FixIndexes(TodoDataContext context, string tableName)
    {
        const string renamePrimaryKeySql = @"
            DECLARE @TableName NVARCHAR(128)
            DECLARE @IndexName NVARCHAR(128)
            DECLARE @OldName NVARCHAR(128)
            DECLARE @NewName NVARCHAR(128)
            SELECT  @TableName = '{0}'

            SELECT  @IndexName = C.CONSTRAINT_NAME
            FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
            WHERE   pk.TABLE_NAME = @TableName
              AND   CONSTRAINT_TYPE = 'PRIMARY KEY'
              AND   C.TABLE_NAME = PK.TABLE_NAME
              AND   C.CONSTRAINT_NAME = PK.CONSTRAINT_NAME

            SELECT  @OldName = @TableName + '.' + @IndexName
            SELECT  @NewName = 'PK_' + @TableName

            exec sp_rename @OldName, @NewName, 'INDEX'";

        context.Database.ExecuteSqlCommand(string.Format(renamePrimaryKeySql, tableName));
+3
source share
1 answer

There is no way to change these names unless you manually put them in a custom initializer and create them again. EF does not have pluggable conventions, so you cannot override them.

0
source

All Articles