Automapper and EF Navigation Properties

asp.net-core asp.net-core-mvc automapper-6 entity-framework-core

Question

With ASP.NET MVC Core and Entity Framework Core I'm trying to create a simple website.

I've defined my Model:

public class Club
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set;  }

    public virtual IEnumerable<Team> Teams { get; set; }
}

public class Team
{
    [Key]
    public int Id { get; set; }

    public int ClubId { get; set; }

    [MaxLength(32)]
    public string Name { get; set; }

    public virtual Club Club { get; set; }
}

As well as the corresponding View Models:

public class ClubViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual IEnumerable<TeamViewModel> Teams { get; set; }
}

public class TeamViewModel
{
    public int Id { get; set; }

    public int ClubId { get; set; }

    public string Name { get; set; }

    public virtual ClubViewModel Club { get; set; }
}

I've defined an Automapper Profile with the corresponding mappers:

    CreateMap<Club, ClubViewModel>();
    CreateMap<ClubViewModel, Club>();
    CreateMap<Team, TeamViewModel>();
    CreateMap<TeamViewModel, Team>();

I try to load a Club entity, with the navigation property Teams included (_context.Club.Include(c => c.Teams).ToList()). This works as expected, it returns a Club with a list of Teams. But when I try to map this instance to a ClubViewModel, I get an 502.3 error and my debug session is ended immediately.

It seems like I am missing something trivial, but I simply do not see it. There's no information in the Windows Event Log and I can't find any usefull information in the IIS Express logging (%userprofile%\documents\IISExpress)

What is causing the crash?

1
1
11/26/2018 2:46:36 PM

Accepted Answer

You can't perform this mapping because it is circular. You'll have to remove this line

public virtual ClubViewModel Club { get; set; }

from your TeamViewModel and the mapping should work as expected.

1
11/26/2018 12:24:38 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow