EF code first - custom foreign key constraint name

▼魔方 西西 提交于 2019-11-28 02:48:09

问题


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.


回答1:


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")
    
            // ...
        }
    }
    



回答2:


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

For more datail plese see the answer



来源:https://stackoverflow.com/questions/17926413/ef-code-first-custom-foreign-key-constraint-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!