使用 LINQ 加载相关实体

Loading related entities with LINQ

我有以下两个class:

作者 class:

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; }
}

还有这本书 class:

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 的作者,我想 return 与该特定作者关联的所有书籍。

我的想法是,最好的方法是使用 LINQ,但是我不知道如何正确创建 LINQ 查询来执行此操作。您能否指导我完成上述任务的最佳方法?

您需要查询图书table。类似于:

IQueryable<Book> books =  
from book in db.Books
where book.AuthorId == 1  
select book; 

看这里 https://msdn.microsoft.com/en-us/library/bb397906.aspx..这是一个很好的起点。

如果您正在使用 entity framework,我会推荐 https://msdn.microsoft.com/en-us/library/bb399375(v=vs.110).aspx

需要先实例化数据库上下文,然后才能用linq访问指定的实体

var dbContext = new DataContext();
var query = from book in dbContext.Books
where book.AuthorId == 1
select book;

之后,您可以在 foreach-loop(或类似的)中获得结果或执行方法

.First();

有例外或

.FirstOrDefault();

无一例外。