Home > Enterprise >  Convert a list of entities to a list of view models
Convert a list of entities to a list of view models

Time:12-01

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:

Publisher ViewModel

This is the method (it works fine):

GetPublisherById Method

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:

GetAllPublishers Method

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();

Loading Related Data - EF Core | Microsoft Docs

  •  Tags:  
  • c#
  • Related