简体   繁体   中英

Map to a collection from another collection with automapper

my AutoMapper configuration looks like this

 public static class AutoMapperConfig
  {
    public static void ConfigureAutoMapper(this IMapperConfigurationExpression cfg)
    {
      cfg.CreateMap<Foo, BarDTO>()
        .ForMember(dto => dto.Genres, o => o.ResolveUsing(b =>
        {
          var retVal = new List<string>();

          foreach (var genre in b.Genres)
          {
            retVal.Add(genre.Genre.GenreName);
          }

          return retVal;
        }));
    }
  }

BarDTO's property Genre is Collection of type string

this ends up in an exception:

System.InvalidOperationException: 'No generic method 'ToList' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. '

if I try this instead:

cfg.CreateMap<Foo, BarDTO>()
.ForMember(dto => dto.Genres, conf => conf.MapFrom
 (
  ol => ol.Genres.Select(tr => tr.Genre.GenreName).ToList())
 );

this doesn't throw any exception but nothing happens. Seems like infinite mapping (loading).

Thank you in advance!

Edit:

Here are my classes. I use Entity-Framework Core 2.0 that's why I have to create the n to m relation with Foo2Genre by myself.

public class BarDTO
{
    public BarDTO()
    {
      Genres = new List<string>();
    }
    public ICollection<string> Genres { get; set; }
}

public class Foo
{
    public Foo()
    {
      Genres = new List<Foo2Genre>();
    }
    public ICollection<Foo2Genre> Genres { get; set; }
}

 public class Foo2Genre 
  {
    public int FooId{ get; set; }
    public Foo Foo{ get; set; }

    public int GenreId { get; set; }
    public Genre Genre { get; set; }
  }

 public class Genre
 {
    public Genre()
    {
      Foos = new List<Foo2Genre>();
    }

    public string GenreName { get; set; }

    public ICollection<Foo2Genre> Foos{ get; set; }
 }

I think you need an Include for Genres. That would work as is in EF6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM