Search code examples
c#entity-frameworkautomapper

Make automapper load relations


Why do I have to use include to make automapper load relations with EF core?

I have a list of ZipFiles with their corresponding File fields. Why doesn't automapper trigger lazy loading automatically for the fields I've defined?

_context.ZipFiles
  .Include(z => z.File) // <- why is this needed?
  .Select(_mapper.Map<Shared.Models.ZipFile>);

The mapping:

CreateMap<DatabaseFile, Shared.Models.DatabaseFile>();
CreateMap<ZipFile, Shared.Models.ZipFile>();

The target model:

public class ZipFile : Entity
{
    public DatabaseFile File { get; set; } = null!;
}

Solution

  • Lazy loading isn't enabled by default. You have to enable it explicitly.

    You can also mark some fields to be always auto included in your query. You will not have to Include them this way.