I am very new to C# and the .NET Framework. I have a function in my PublisherService
to retrieve a publisher by it's Id. It maps the Publisher
to a view model that has the Publishername
and a list of BookAuthorsVM
.
You can see the classes here:
This is the method (it works fine):
Now I am trying to write a method that retrieves all publishers with their books. This is what i have but it is throwing a Null error:
Any suggestions how to do this? Do I need a foreach instead?
Best Regards, Anthony
CodePudding user response:
At a guess, you're using Entity Framework Core as your ORM.
EF Core doesn't use lazy-loading by default. When you load an entity into memory, its navigation properties will not be populated.
Your GetPublisherById
method works, because the query is translated into SQL and executed on the server.
Your GetAllPublishers
method doesn't work because you have a .ToList()
call before the .Select(...)
call, which forces the query to execute in-memory. Since you haven't told the query to include any of the related data, the q.Books
collection is null
.
You should be able to get the query to work by removing the first .ToList()
call:
var _publisherData = _context.Publishers.Select(q => new PublisherWithBooksAndAuthorsVM
{
...
}).ToList();