ahmad valipour
ahmad valipour

Reputation: 303

Add entity in many to many relationship in Entity Framework

I have a many to many relationship in my code first.

public class Post
{
    public int Id { get; set; }
    public ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public ICollection<Post> Posts { get; set; }
}

modelBuilder.Entity<Post>().HasMany(c => c.Tags).WithMany(a => a.Posts);    

If i have a PostId and a TagId , How i can insert relationship with single query in entity framework (Without load Post or Tag and add relationship to that)

Upvotes: 2

Views: 108

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205939

This is one of the drawbacks of the implicit junction table.

Still it's possible to do what you are asking by creating two "stub" entities, attach them to the context (this telling EF that they are existing), and adding one of them to the collection of the other:

using (var db = new YourDbContext())
{
    var post = db.Posts.Attach(new Post { Id = postId });
    var tag = db.Tags.Attach(new Tag { Id = tagId });
    post.Tags = new List<Tag> { tag };
    db.SaveChanges();
}

Due to the hack-ish nature of above technique, make sure to use it only with short lived contexts specifically allocated for the operation.

Upvotes: 1

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

If I understood your question correctly, you want to ignore the insertion of navigation property. You can change state of the collection property as 'UnChanged' to avoid insertion of the property.

It will looks like;

_context.Posts.Add(post);

_context.Entry(post.Tags).State = EntityState.Unchanged;

_context.SaveChanges();

Upvotes: 0

Related Questions