entity-framework - Entity Framework 代码优先 : Adding to Many to Many relationship by ID

标签 entity-framework ef-code-first

我有一个多对多关系定义如下:

public class Post
{
   //NOT SHOWN: Other properties
   public virtual ICollection<Tag> Tags { get; set; }
}

我看到的所有示例都会添加到这样的多对多关系中:

//Get the tag with ID of 1
var tag = context.Tags.Find(1);
// associate tag with ID of 1 with myPost
myPost.Tags.Add(tag);

但是,如果我只知道我想与我的帖子关联的标签的 id,这似乎很乏味/低效。

理想情况下,我只想公开 List<int> TagIds在我的 Post 实体上,并能够通过将标签 Id 添加到列表来添加标签,但我无法确定是否可以使用 EF Code First 来实现这一点。

底线:鉴于我只有想要关联的实体的 ID,将项目添加到多对多关系的最佳方法是什么。 (例如,如果我有一个标签 ID 列表,将这些标签与帖子相关联的最佳方式是什么?)

最佳答案

使用这样的代码:

// Existing post without loading it from the database
var myPost = new Post() { Id = ... };
context.Posts.Attach(post);

// For each id of existing tag 
foreach (int tagId in someExistingTagIds)
{
    var tag = new Tag() { Id = tagId };
    context.Tags.Attach(tag);

    // Make a new relation
    post.Tags.Add(tag);
}

context.SaveChanges();

这将允许您在现有实体上创建 M-N 关系,而无需从数据库加载任何内容。您只需要知道现有实体的 ID。

关于entity-framework - Entity Framework 代码优先 : Adding to Many to Many relationship by ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478570/

相关文章:

asp.net-mvc - Linq lambda 空合并可空 int

c# - 尝试将对象与 EntityFramework 关联时出现无效列名错误

ef-code-first - EF 4.1 代码首先导致奇怪的(登录)运行时错误

.net - 模型存储 edmx 文件不会在 Debug模式下生成,但会在 Release模式下生成

c# - 无法确定主体端 - Entity Framework 代码优先关系

entity-framework - Entity Framework 中的单例数据库模式

c# - 将图像添加到数据库

c# - EF 包含 where 子句

c# - Entity Framework ,代码优先。调用时不填充子对象

c# - 通过 DataAnnotation 强制外键列名称不起作用