首先是EF代码 - 自定义外键约束名称

MrH*_*key 14 ef-code-first entity-framework-5

我想知道在使用代码时是否有机会更改Entity Framework生成的外键约束的名称.

我有两个实体 - UserGroup- 具有多对多关系,因此有一个关联表GroupUser.不幸的是,自动生成的外键约束被命名为FK_dbo.GroupUser_dbo.User_User_UserIdFK_dbo.GroupUser_dbo.Group_Group_GroupId.

我想有外键约束称为FK_GroupUser_UserIdFK_GroupUser_GroupId.这对我来说看起来更干净.

Sla*_*uma 7

无法使用数据注释或DbModelBuilderFluent API 自定义外键约束名称.但是,您可以使用基于代码的迁移来控制名称.

  • 第一个选项:通过迁移创建表时:

    为连接表自动生成的迁移代码如下所示:

    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);
    
            // ...
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    在这里,您可以修改两个ForeignKey方法调用以在调用之前设置自定义约束名称update-database:

            .ForeignKey("User", t => t.UserId, cascadeDelete: true,
                name: "FK_GroupUser_UserId")
            .ForeignKey("Group", t => t.GroupId, cascadeDelete: true,
                name: "FK_GroupUser_GroupId")
    
    Run Code Online (Sandbox Code Playgroud)
  • 第二个选项:当表已经存在时,您可以删除约束并在迁移中添加新重命名的约束:

    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")
    
            // ...
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)