使用 EF Core 5 多对多关系与具有额外数​​据的“连接表”

1 entity-framework entity-framework-core

我想问是否有人可以帮助我使用 EF Core 5。我有两个处于“多对多”关系的表:在 Join 表上,除了充当外键的列之外,我还有其他我想要在 EF Core 中映射的列。我能想到的唯一解决方案是像 EF Core 3 中那样创建关系,即使用与联接表的“一对多”关系。

有什么建议么?

谢谢。

诗。对不起我的英语不好。

Dav*_*oft 8

我能想到的唯一解决方案是像 EF Core 3 中那样创建关系,即使用与联接表的“一对多”关系。

你可以鱼与熊掌兼得。

EF Core 5 支持自定义链接实体并同时使用跳级导航。

文档中有一个示例,其中链接实体位于模型中,具有其他属性,但主要实体使用集合导航属性跳过链接实体。

internal 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; }
}
Run Code Online (Sandbox Code Playgroud)

PostTag是一个常规实体,您可以通过db.Set<PostTag>()帖子或标签访问它。请注意(可选)导航属性 fromPostTagto PostTag

  • 谢谢,@DavidBrowne!即使有文档链接(它似乎不包含您提取的代码,顺便说一句),我也永远不会在一百万年内弄清楚这一点。 (2认同)