【问题标题】:How to combine one-to-many relationship and many-to-many relationship in Entity Framework Core如何在 Entity Framework Core 中结合一对多关系和多对多关系
【发布时间】:2021-07-31 20:31:44
【问题描述】:

我的要求是:帖子由用户(作者)创建,可以在帖子中标记许多用户(TaggedUsers)。一个用户可以创建很多帖子(CreatedPosts),一个用户可以在很多帖子中被标记(TaggedPosts)。所以我创建了 2 类实体 Post 和 User,如下所示。

public class Post
{
  public int Id {get; set;}
  public string Title {get; set;}
  public string Body {get; set;}
  public User Author {get; set;}
  public ICollection<User> TaggedUsers {get; set;}
}
public class User
{
  public int Id {get; set;}
  public string Username {get; set;}
  public ICollection<Post> CreatedPosts {get; set;}
  public Collection<Post> TaggedPosts {get; set;}
}

那么我如何在代码优先的方法中配置关系(使用 Fluent API 或数据注释)。 数据库应该有 3 个表:Users、Posts、PostTags。

用户:

  • 身份证
  • 用户名

帖子:

  • 身份证
  • User_id
  • 标题
  • 身体

帖子标签:

  • 身份证
  • Post_id
  • User_id

非常感谢您的帮助。

【问题讨论】:

标签: sql-server .net-core entity-framework-core


【解决方案1】:

这是您尝试做的一个示例:

class MyContext : DbContext
{
   public MyContext(DbContextOptions<MyContext> options)
      : base(options)
  {
  }

public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasMany(p => p.Tags)
        .WithMany(p => p.Posts)
        .UsingEntity<PostTag>(
            j => j
                .HasOne(pt => pt.Tag)
                .WithMany(t => t.PostTags)
                .HasForeignKey(pt => pt.TagId),
            j => j
                .HasOne(pt => pt.Post)
                .WithMany(p => p.PostTags)
                .HasForeignKey(pt => pt.PostId),
            j =>
            {
                j.Property(pt => pt.PublicationDate).HasDefaultValueSql("CURRENT_TIMESTAMP");
                j.HasKey(t => new { t.PostId, t.TagId });
            });
}

}

 public class Post
 {
  public int PostId { get; set; }
  public string Title { get; set; }
  public string Content { get; set; }

  public ICollection<Tag> Tags { get; set; }
  public List<PostTag> PostTags { get; set; }

}

public class Tag
{
   public string TagId { get; set; }

   public ICollection<Post> Posts { get; set; }
   public List<PostTag> PostTags { get; set; }

}

 public class PostTag
 {
    public DateTime PublicationDate { get; set; }

    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

【讨论】:

  • 我将用我的用户替换代码中的标签实体。所以我必须创建第三个实体 PostTag。
  • 在你的例子中,它不包括我的重要作者字段,它是一个用户对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 2019-06-18
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多