如何在EF中加载相关对象?

时间:2014-01-01 07:51:28

标签: wpf entity-framework lazy-loading

我在EF Code First中有3个模型:

public class Book
{
 public int Id { get; set; }
 public ICollection<Author> Authors{ get; set; }
}

public class Author
 {
  public int Id { get; set; }
  [Required(ErrorMessage = "")]
  [ForeignKey("AuthorName")]
  public int AuthorId{ get; set; }
  public User AuthorName{ get; set; }
  public bool Signed {get; set;}
  }

public class User
 {
 public int Id { get; set; }
 public string Name{ get; set; }
 }

我使用此代码选择BookId的所有AuthorName。

db.Book.Find(BookId).Authors.Where(e => e.Signed == false);

但是AuthorName为空。

如何加载相关对象?

2 个答案:

答案 0 :(得分:2)

这将在一个查询中加载所有内容:

from b in db.Book
where b.Id == BookId
from a in b.Authors
where !a.Signed
select a.AuthorName.Name

流利的等价物是

db.Books.Where(b => b.Id  == BookId)
        .SelectMany(b => b.Authors.Where(a => !a.Signed)
        .Select(a => a.AuthorName.Name)

语句db.Book.Find(BookId)从数据库加载一个Book。之后,您只能通过延迟加载加载AuthorUserFind无法与Include结合使用。

答案 1 :(得分:0)

恕我直言,即使您的Authors应该为空,因为您没有为延迟加载设置实体。如果您使AuthorsAuthorName虚拟,您的查询应该可以正常工作,但它最多可以导致3个单独的数据库查询。