ar.gorgin
ar.gorgin

Reputation: 5002

How to Load Related Objects in EF?

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

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

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

Gert Arnold
Gert Arnold

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 Authors and Users by lazy loading. Find can't be combined with Include.

Upvotes: 2

Related Questions