1

Since the many-to-many relationship is not supported in Entity Framework 7 yet,

I'm following work around in this link.

Here is the code from the link above:

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

Question

How can I associate a Tag to a Post? In other words how can I add a row to the junction table?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128

1 Answers1

0

Here's my answer to another SO question where the method I came up with is explained.

Create your Tag instance and add it to Tags. Do the same with the Post instance, initializing its PostTags navigation property, and add it to Posts.
Then create the PostTag instance, initializing it with both Post and Tag instances.
Finally call SaveChanges or SaveChangesAsync methods.

This will allow EF to properly manage ID properties before writing all the involved entities to the underlying DB.

Community
  • 1
  • 1
m.phobos
  • 283
  • 1
  • 3
  • 12