在实体框架中以多对多关系添加实体

编程入门 行业动态 更新时间:2024-10-28 06:29:39
本文介绍了在实体框架中以多对多关系添加实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

在实体框架中以多对多关系添加实体

本文发布于:2023-10-26 11:11:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529964.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   中以   框架   关系

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!