开发者

DbContext - Many to Many reliationship between three tables

Well i've been tring for some time to make Many-to-Many relationship between three tables. Forum, Role, AccessMask. In SQL It would like this:

ForumID | RoleID | AccessMaskID
--------------------------------
1       | 1      | 2
2       | 2      | 1

And so on. You got the idea. ForumID and RoleID is primary key for table. Question is.. how to do it in DbContext ? It alawys screaming that ent开发者_开发百科ity is missing key. (really ?). I found a way to make and many-to-many relationship between two tables with modelBuilder, but as you see I still will be missing one more table


This will not be many-to-many relationship. You must expose this table as separate entity and map three one-to-many relationships. Many-to-many relationship works only between two tables if junction table contains only keys of these tables.

public class Forum
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; } 
}

public class Role
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; } 
}

public class AccessMask
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; } 
}

public class ForumRole
{
    [Key, Column(Order = 0)]
    public int ForumId { get; set; }
    [Key, Column(Order = 1)]
    public int RoleId { get; set; }
    public int AccessMaskId { get; set; }

    public virtual Forum Forum { get; set; }
    public virtual Role Role { get; set; }
    public virtual AccessMask AccssMask { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜