我的代码中首先有很多关系。
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);如果我有 PostId 和 TagId ,如何在实体框架中插入单个查询的关系(不加载 Post 或 Tag 并为其添加关系)
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)
推荐答案这是隐式联结表的缺点之一。
This is one of the drawbacks of the implicit junction table.
仍然可以通过创建两个存根实体,将它们附加到上下文(这告诉EF它们存在),并添加一个来完成您要的操作
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(); }由于上述技术具有hack-ish性质,因此请务必使用仅在为该操作专门分配的短暂上下文的情况下。
Due to the hack-ish nature of above technique, make sure to use it only with short lived contexts specifically allocated for the operation.
更多推荐
在实体框架中以多对多关系添加实体
发布评论