【问题标题】:Defining many to many relationship定义多对多关系
【发布时间】:2020-04-08 00:50:06
【问题描述】:

我正在努力定义以下关系:

  1. 一个用户可以有很多帖子。
  2. 用户可以作为协作者参与许多帖子。
  3. 帖子只有一个所有者。
  4. 一个帖子可以有许多用户(即合作者)。 (所有者可以稍后添加)
    Class User(){
       public Guid Id{ get; set; }
    }

    class UserPost(){
       public Guid UserId { get; set; }
       public User User { get; set; }

       public Guid PostId { get; set; }
       public { get; set; }
    }

    class Post(){
       public IList<UserPost> UserPost{ get; set; }
       public Guid AuthorId { get; set; }
       public User Author { get; set; }
       public string Title { get; set; }
    }

我的代码是否正确表示了这种关系?

【问题讨论】:

  • 我认为 #3 和 #4 点可能与 #1 和 #2 相同。我说的对吗?
  • 嗨,Alex,欢迎来到 SO。合作者的代表在哪里?另外,如果 Post 有一个 Guid AuthorId 对象(外键),它不必也有一个 User 对象(所有权/依赖关系),我是否正确理解 AuthorId 将与 Author.Id 相同?最后,什么是 public { get;放; } 目的?这在语法上是不正确的。
  • 您好,谢谢。 :) 协作者是用户。我正在学习教程,他们还在那里创建了 Author 属性。

标签: asp.net-core entity-framework-core


【解决方案1】:

每一个都需要是一个单独的关系。这意味着你需要这样的东西:

public class User
{
    public ICollection<Post> Posts { get; set; }
    public ICollection<PostCollaborator> CollaboratingPosts { get; set; }
}

public class Post
{
    public User Owner { get; set; }
    public ICollection<PostCollaborator> Collaborators { get; set; }
}

public class PostCollaborator
{
    public Post Post { get; set; }
    public User Collaborator { get; set; }
}

换句话说,帖子所有者关系实际上是一对多的。一个用户可以拥有许多帖子,但每个帖子只有一个所有者。后期协作者关系是多对多的,则需要加入实体PostCollaborator

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 2021-12-26
    • 1970-01-01
    • 2015-04-02
    • 2015-02-03
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多