将一个表ID分配给另一个表ID,如Asp.Net Identity AspNetUserRole

时间:2015-07-09 14:16:05

标签: asp.net asp.net-mvc vb.net linq visual-studio-2013

我有3个模型类设置Group

Public Class Group
    Public Property Id As Long
    Public Property Name As String
    Public Property CoverImgUrl As String
    Public Overridable ReadOnly Property Profile() As ICollection(Of Profile)
        Get

        End Get

    End Property
End Class

Profile

Public Class Profile
    Public Property Id As Long
    <Required>
    <MaxLength(20)>
    <Display(Name:="First Name")>
    Public Property FirstName As String
    <Required>
    <MaxLength(20)>
    <Display(Name:="Last Name")>
    Public Property LastName As String
 Public Overridable ReadOnly Property Group() As ICollection(Of Group)
        Get

        End Get

    End Property

GroupMembers

Public Class GroupMembers
    Public Sub New()
    End Sub
    Public Overridable Property Group() As Group
    Public Overridable Property GroupId() As String
    Public Overridable Property Profile() As Profile
    Public Overridable Property ProfileId() As String
End Class

我运行了Update-Database命令来更新我的数据库,并创建了一个像{asp.net ProfileGroup这样的表AspNetUserRole

enter image description here

到目前为止,我如何将一个组分配给我创建的配置文件,如asp.net使用UserManager.AddToRole方法将用户分配给角色或任何全局最佳实践。感谢

1 个答案:

答案 0 :(得分:0)

您似乎只是想在ProfileGroup之间建立多对多关系。但是,你一切都错了。

首先,传统上,在这种情况下,您实际上并没有为中间表GroupMembers定义一个类,除非您需要有效负载,即关系的其他数据。在您发布的代码中,关系中没有任何有效负载,因此您只是通过这种方式让生活变得更加困难。但是,假设您希望保持原样,则需要设置类:

Public Class Group
    ...

    Public Overridable Property Profiles As ICollection(Of GroupMember)

End Class

Public Class Profile
    ...

    Public Overridable Property Groups As ICollection(Of GroupMember)

End Class

Public Class GroupMember
    Public Property GroupId As String
    Public Overridable Property Group As Group

    Public Property ProfileId As String    
    Public Overridable Property Profile As Profile    
End Class

这将足以让Entity Framework识别关系并使用适当的外键创建适当的表。但是,您将被迫间接访问Profile / Group,即profile.Groups.First().Group。然而,使用隐式连接表,您可以执行profile.Groups.First()

因此,为了拥有隐式连接表,您只需要以下类:

Public Class Group
    ...

    Public Overridable Property Profiles As ICollection(Of Profile)

End Class

Public Class Profile
    ...

    Public Overridable Property Groups As ICollection(Of Group)

End Class

请注意,GroupMember类完全消失了。实体框架仍会将此视为多对多并创建一个表,很可能名为dbo.GroupProfiles。如果您对表名不满意,可以使用流畅的配置声明它:

modelBuilder.Entity(Of Profile)().
    HasMany(Function(t) t.Groups).
    WithMany(Function(t) t.Profiles).
    Map(Sub(m)
            m.ToTable("GroupMembers")
        End Sub)