我在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为此是null。
如何加载相关对象?
这将在一个查询中加载所有内容:
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
。之后,您只能通过延迟加载来加载Author
s和User
s。Find
不能与结合使用Include
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句