Reputation: 5002
I have 3 models in EF Code First:
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; }
}
I use this code for select all AuthorName of BookId .
db.Book.Find(BookId).Authors.Where(e => e.Signed == false);
But AuthorName is null for this.
How to Load Related Objects?
Upvotes: 0
Views: 82
Reputation: 364259
IMHO even your Authors
should be empty because you don't have your entities setup for lazy loading. If you make Authors
and AuthorName
virtual your query should work but it can cause up to 3 separate queries to database.
Upvotes: 0
Reputation: 109079
This will load everything in one query:
from b in db.Book
where b.Id == BookId
from a in b.Authors
where !a.Signed
select a.AuthorName.Name
The fluent equivalent is
db.Books.Where(b => b.Id == BookId)
.SelectMany(b => b.Authors.Where(a => !a.Signed)
.Select(a => a.AuthorName.Name)
The statement db.Book.Find(BookId)
loads one Book
from the database. After that, you can only load Author
s and User
s by lazy loading. Find
can't be combined with Include
.
Upvotes: 2