【发布时间】:2017-02-08 05:31:18
【问题描述】:
我有以下两个类:
作者类别:
public class Author
{
public Author()
{
this.Books = new List<Book>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
还有书类:
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DatePublished { get; set; }
public bool IsBorrowed { get; set; }
public bool IsOverdue { get; set; }
public int AuthorId { get; set; }
public virtual Author Author { get; set; }
}
一个作者可以有很多本书。我遇到的问题是加载与作者相关的所有书籍。例如,我的数据库中有一个 ID 为 1 的作者,我想返回与该特定作者关联的所有书籍。
我的想法是,最好的方法是使用 LINQ,但是我不知道如何正确创建 LINQ 查询来执行此操作。您能否指导我完成上述任务的最佳方法?
【问题讨论】:
-
db.Authors.Find(1)?.Books -
var books = context.Books.Where(b => b.AuthorId == 1);如果您还想要作者信息:var authorAndBooks = context.Authors.Include(a => a.Books).FirstOrDefault(a => a.Id == 1); -
您标记了 linq-to-sql 但您的示例类没有
-
@Pleun 他们确实是。我只是省略了不相关的代码以使问题简短直接。如果这造成任何混乱,我们深表歉意。
标签: c# entity-framework linq linq-to-sql loading