Add entity in many to many relationship in Entity Framework

爱⌒轻易说出口 提交于 2019-12-11 02:24:58

问题


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)


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/47960981/add-entity-in-many-to-many-relationship-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!