How to fix duplicate foreign key when adding navigation property to existing relationship?


I have a very simply identity object:

Public Class UserRole
    Inherits IdentityUserRole(Of Integer)
End Class

By default this generated the following migration:

    Function(c) New With
            .UserId = c.Int(nullable := False),
            .RoleId = c.Int(nullable := False)
        }) _
    .PrimaryKey(Function(t) New With { t.UserId, t.RoleId }) _
    .ForeignKey("dbo.Users", Function(t) t.UserId) _
    .ForeignKey("dbo.Roles", Function(t) t.RoleId) _
    .Index(Function(t) t.UserId) _
    .Index(Function(t) t.RoleId)

A foreign key exists to the Roles table, but I did not define a navigation property for UserRole.Role and one does not exist on the object.

When I try to add one:

Public Class UserRole
    Inherits IdentityUserRole(Of Integer)

    Public Overridable Property Role() as Role
End Class

This generates the following migration:

Public Overrides Sub Up()
    AddForeignKey("dbo.UserRoles", "RoleId", "dbo.Roles", "Id")
End Sub

And then the site throws an error when trying to migrate:

System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'FK_dbo.UserRoles_dbo.Roles_RoleId' in the database. Could not create constraint or index.

Why is it trying to generate the foreign key a second time? Shouldn't it be able to see the existing foreign key from the initial migration?

Is there anything I can do to fix this?
asked on Stack Overflow Nov 8, 2016 by hobwell • edited Jul 11, 2019 by hobwell

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0