Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wonder if there is any chance to change name of foreign key constraint generated by Entity Framework when using code first.

I have two entities - User and Group - with many-to-many relationship so there is an association table GroupUser. Unfortunately, auto-generated foreign key constraints are named FK_dbo.GroupUser_dbo.User_User_UserId and FK_dbo.GroupUser_dbo.Group_Group_GroupId.

I would like to have foreign key constraints called like FK_GroupUser_UserId and FK_GroupUser_GroupId. That looks much cleaner to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
819 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's not possible to customize the foreign key constraint name with data annotations or DbModelBuilder Fluent API. However, you can control the name with code-based migrations.

  • First option: When the tables get created via migrations:

    The migration code that gets automatically generated for the join table would look like this:

    public partial class MyMigration : DbMigration
    {
        public override void Up()
        {
            CreateTable("GroupUser",
                c => new
                {
                    UserId = c.Int(nullable: false),
                    GroupId = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.UserId, t.GroupId })
            .ForeignKey("User", t => t.UserId, cascadeDelete: true)
            .ForeignKey("Group", t => t.GroupId, cascadeDelete: true)
            .Index(t => t.UserId)
            .Index(t => t.GroupId);
    
            // ...
        }
    }
    

    Here you can modify the two ForeignKey method calls to set a custom constraint name before you call update-database:

            .ForeignKey("User", t => t.UserId, cascadeDelete: true,
                name: "FK_GroupUser_UserId")
            .ForeignKey("Group", t => t.GroupId, cascadeDelete: true,
                name: "FK_GroupUser_GroupId")
    
  • Second option: When the tables already exist you can drop the constraint and add a new renamed one in a migration:

    public partial class MyMigration : DbMigration
    {
        public override void Up()
        {
            DropForeignKey("UserGroup", "UserId", "User");
            DropForeignKey("UserGroup", "GroupId", "Group");
    
            AddForeignKey("UserGroup", "UserId", "User",
                name: "FK_GroupUser_UserId");
            AddForeignKey("UserGroup", "GroupId", "Group",
                name: "FK_GroupUser_GroupId")
    
            // ...
        }
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...