【问题标题】:Insert into the junction table in EF 7在 EF 7 中插入连接表
【发布时间】:2016-06-17 07:07:12
【问题描述】:

由于 Entity Framework 7 尚不支持多对多关系,

我正在关注这个link 的工作。

这是上面链接中的代码:

class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

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

    public List<PostTag> PostTags { get; set; }
}

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

    public List<PostTag> PostTags { get; set; }
}

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

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

问题

如何将TagPost 关联? 换句话说,我怎样才能在联结表中添加一行?

【问题讨论】:

  • 你尝试过类似MyPost.PostTags.Add(new PostTag(){ ... })的方法吗?

标签: ef-code-first many-to-many relational-database entity-framework-core


【解决方案1】:

这是我对another SO question 的回答,其中解释了我想出的方法。

创建您的 Tag 实例并将其添加到标签。对 Post 实例执行相同操作,初始化其 PostTags 导航属性,并将其添加到 Posts
然后创建PostTag 实例,同时使用PostTag 实例对其进行初始化。
最后调用SaveChangesSaveChangesAsync 方法。

这将允许 EF 在将所有相关实体写入底层数据库之前正确管理 ID 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2019-08-24
    • 2019-03-27
    相关资源
    最近更新 更多