DbContext - 三个表之间的多对多关系

发布于 2024-11-08 03:56:53 字数 335 浏览 0 评论 0原文

好吧,我已经尝试了一段时间在三个表之间建立多对多关系。 论坛、角色、AccessMask。 在 SQL 中它会像这样:

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

等等。你明白了。 ForumID 和 RoleID 是表的主键。问题是..如何在 DbContext 中做到这一点? 它总是尖叫着实体丢失了钥匙。 (真的 ?)。我找到了一种使用模型构建器在两个表之间建立多对多关系的方法,但正如你所见,我仍然会缺少一个表

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 entity 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月竹挽风 2024-11-15 03:56:54

这不会是多对多的关系。您必须将此表公开为单独的实体并映射三个一对多关系。如果联结表仅包含这些表的键,则多对多关系仅在两个表之间有效。

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; }
}

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; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文