EntityFramework 6.如何获取相关对象? [英] EntityFramework 6. How to get related objects?
问题描述
我的项目中有两个或更多个相关表。
并且需要获取相关对象。
I have two and more related tables in my project. And need to get related objects.
这就是我所做的: http://pastebin.com/BbkT8zvd
并试图像这样:
using (LocalContext _db = new LocalContext())
{
var list = _db.Document.ToList();
foreach (var item in list)
{
Console.WriteLine(item.Name+ ": ");
foreach (var item2 in item.Comment)
{
Console.WriteLine(item2.CommentText);
}
}
}
它不返回与以下内容相关的评论文档。
It returns no comments related with documents.
尝试过惰性,急切和显式的加载方法。
Tried Lazy, Eager and Explicit loading methods.
我应该在代码中更正什么?
What should I correct in my code?
推荐答案
您可以使用紧急加载来获取相关实体,可以通过使用Include方法来实现快速加载:
You can use eager loading for getting related entities, Eager loading is achieved by use of the Include method:
_db.Document.Include("Comment").ToList();
更新:您无需初始化<$ c Comment
类中的$ c> Document ,您的 Comment
类应如下所示:
Update: You don't need to initialize Document
in the Comment
class, Your Comment
class should be like this:
public class Comment
{
public int Id { get; set; }
public int DocId { get; set; }
public string CommentText { get; set; }
public virtual Document Document { get; set; }
}
Document
类:
public class Document
{
public Document()
{
this.Comment = new HashSet<Comment>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public virtual ICollection<Comment> Comment { get; set; }
}
查询:
var list = _db.Document.Include("Comment").ToList();
在这种情况下,将加载所有相关注释。
In this case all related comments will be loaded.
这篇关于EntityFramework 6.如何获取相关对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!