Cristian Szpisjak
Cristian Szpisjak

Reputation: 2469

How to load all levels using Entity Framework Core

My domain model is:

Book

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ReleaseYear { get; set; }

    public virtual ICollection<Store> Stores { get; set; }
}

Store

public class Store
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int BookId { get; set; }

    public virtual Book Book { get; set; }
    public virtual ICollection<StoreLocation> Locations { get; set; }
}

StoreLocation

public class StoreLocation
{
    public int Id { get; set; }
    public string Address { get; set; }
    public int StoreId { get; set; }

    public virtual Store Store { get; set; }
}

How can include all the levels (and sublevels) of a Book?

public Book GetBookById(int Id)
{
    return this._DbContext.Books
        .Include(p => p.Stores)
        .FirstOrDefault(p => p.Id == Id);
}

What i tried?

Upvotes: 1

Views: 98

Answers (1)

Sampath
Sampath

Reputation: 65860

You have to do it as shown below.

  return this._DbContext.Books.Include(p => p.Stores).ThenInclude(q => q.Locations)
                    .FirstOrDefault(p => p.Id == Id);

Note : Sometimes VS doesn't show intelisence properly.So beware of intellisense :D .One solution may be for that is,close the VS and restart new instance of it.If it doesn't work, just type what you want without relying on the intelisence. After that it compiles and works properly.

Upvotes: 1

Related Questions