在实体框架中以多对多关系添加实体 [英] Add entity in many to many relationship in Entity Framework

查看:90
本文介绍了在实体框架中以多对多关系添加实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中首先有很多关系。

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.

这篇关于在实体框架中以多对多关系添加实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆