简体   繁体   English

实体框架在不同集合中多次引用同一对象

[英]Entity Framework referencing the same object multiple times in different collections

I was just playing around with this Code First example for Entity Framework and I encountered a problem which I don't understand. 我只是在玩这个Entity Framework的Code First示例 ,遇到了一个我不理解的问题。 Assuming that the POCO objects and the database context are the same as in the example and that I have the following code in my application's entry point: 假定POCO对象和数据库上下文与示例中相同,并且在应用程序的入口点中具有以下代码:

var blog = new Blog { Name = "My Blog" };
var post = new Post {Title = "A Random Post", Blog = blog};
blog.Posts = new List<Post> {post};
db.Blogs.Add(blog);

var blog2 = new Blog {Name = "Another Blog", Posts = new List<Post> {post}};
db.Blogs.Add(blog2);

db.SaveChanges();

// Display all Blogs from the database
var query = from b in db.Blogs
            orderby b.Name
            select b;

Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
    Console.WriteLine(item.Name);
    foreach (var p in item.Posts)
    {
        Console.WriteLine(p.Title);
    }
}

Why does the post, which is referenced in both blogs, appear only in the second blog? 为什么两个博客中都引用的帖子仅出现在第二个博客中? Do I have to call SaveChanges every time I add something to the database? 每次向数据库添加内容时都必须调用SaveChanges吗?

A post can only belong to one blog. 帖子只能属于一个博客。 By adding it to the list of posts of the second blog, the reference to the first blog gets overwritten. 通过将其添加到第二个博客的帖子列表中,对第一个博客的引用将被覆盖。

It appears that your Blog and Post entities have a many-to-many relationship. 您的Blog和Post实体似乎具有多对多关系。 Have you configured this relationship in the DbContext? 您是否在DbContext中配置了此关系?

Example here: EF Code First working with many-to-many relationships 此处的示例: EF代码首先处理多对多关系

If many-to-many is not your intent, then see Kristof's answer. 如果不是多对多的意图,请参阅Kristof的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM