2

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?

RAM
  • 2,257
  • 2
  • 19
  • 41
Rhapsody
  • 6,017
  • 2
  • 31
  • 49
  • this line `_context.Club.Include(c => c.Teams).ToList()` has nothing to do with Automapper, put this line inside of `try/catch` statement and see what is the exception. – Mohsen Esmailpour Mar 24 '17 at 15:09
  • That line returns a Club instance with the Teams property filled. When I try to map the instance to a ClubViewModel instance using IMapper.Map(club_instance); No exception is caught, the debug session simply ends – Rhapsody Mar 24 '17 at 15:20
  • 1
    Sounds like [circular reference](https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide#circular-references) issue. – Ivan Stoev Mar 24 '17 at 15:47

1 Answers1

3

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.

RAM
  • 2,257
  • 2
  • 19
  • 41
Eric B
  • 4,367
  • 5
  • 33
  • 43