[英]Loading related entities with LINQ
I have the following two classes: 我有以下两节课:
Author 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; }
}
And the Book class: 和Book类:
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; }
}
An author can have many books. 作者可以有很多书。 What I am having trouble with is loading all the books associated with an Author.
我遇到的麻烦是加载与作者相关的所有书籍。 For example I have an Author in my database with an ID of 1, I want to return all the books associated with that particular Author.
例如,我的数据库中有一位Author,ID为1,我想返回与该特定Author相关的所有书籍。
My thought process was that the best way to do this is with LINQ, however I am lost on how to properly create a LINQ query to do this. 我的想法是,最好的方法是使用LINQ,但是我迷失了如何正确创建LINQ查询的方法。 Could you please guide me on the best way to accomplish said task?
您能指导我完成上述任务的最佳方法吗?
Look here https://msdn.microsoft.com/en-us/library/bb397906.aspx .. Thats a good site to start with. 在这里查看https://msdn.microsoft.com/zh-cn/library/bb397906.aspx ..那是一个很好的起点。
If you are working with entity framework I´ll recommend https://msdn.microsoft.com/en-us/library/bb399375(v=vs.110).aspx 如果您正在使用实体框架,我将建议https://msdn.microsoft.com/zh-cn/library/bb399375(v=vs.110).aspx
You need to instantiate the database context first, and after that you can access the specified entity with linq 您需要首先实例化数据库上下文,然后可以使用linq访问指定的实体。
var dbContext = new DataContext();
var query = from book in dbContext.Books
where book.AuthorId == 1
select book;
After that you can either get your results in a foreach-loop (or such) or executing the methods 之后,您可以在foreach循环(或类似的循环)中获得结果,或者执行方法
.First();
With exceptions or 例外或
.FirstOrDefault();
without exceptions. 没有例外。
You need to query the books table. 您需要查询books表。 Something like:
就像是:
IQueryable<Book> books =
from book in db.Books
where book.AuthorId == 1
select book;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.