Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# Entity Framework Basics LINQ Queries Loading Related Entities

Alex Hedley
Alex Hedley
16,378 Points

Load Artists for ComicBook

In program.cs there is a method

private static void ListComicBook(int comicBookId)

This loads the comicbook then loops the Artists:

ComicBook comicBook = Repository.GetComicBook(comicBookId);

foreach (ComicBookArtist artist in comicBook.Artists)
{
    ConsoleHelper.OutputLine("{0} - {1}", artist.Artist.Name, artist.Role.Name);
}

If we wanted to add a Repository method to return a List of Artists can this be done in Linq?

public IEnumerable<Artist> GetArtistsForComicBook(int comicBookId)

We have

return context.ComicBooks
    .Include(cb => cb.Artists)
    .Where(cb => cb.Id == comicBookId)
    .SingleOrDefault();

Can you make a Select to just return the cb.Artists.Artist List Since cb.Artists is a ComicBookArtist and I actually want a List of Artist

1 Answer

Steven Parker
Steven Parker
221,297 Points

I believe you can do this with a one-liner.

You don't need LINQ just to get a list:

    return Repository.GetComicBook(comicBookId).Artists.ToList();
Alex Hedley
Alex Hedley
16,378 Points

I'm getting the following error at first go, but I'll look into it

Cannot implicitly convert type 'System.Collections.Generic.List<ComicBookLibraryManager.Models.ComicBookArtist>' to 'System.Collections.Generic.IEnumerable<ComicBookLibraryManager.Models.Artist>'. An explicit conversion exists (are you missing a cast?)

Steven Parker
Steven Parker
221,297 Points

You could cast the result, or just define the method to return a list:

public List<Artist> GetArtistsForComicBook(int comicBookId)
{
    return Repository.GetComicBook(comicBookId).Artists.ToList();
}