繁体   English   中英

使用自动映射器映射到另一个集合中的一个集合

[英]Map to a collection from another collection with automapper

我的AutoMapper配置看起来像这样

 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的属性Genre是字符串类型的集合

最终导致异常:

System.InvalidOperationException:'类型'System.Linq.Enumerable'上的通用方法'ToList'与所提供的类型实参和实参兼容。 如果方法是非泛型的,则不应该提供任何类型参数。

如果我尝试这样做:

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

这不会引发任何异常,但是什么也不会发生。 好像是无限映射(加载)。

先感谢您!

编辑:

这是我的课。 我使用Entity-Framework Core 2.0,这就是为什么我必须自己使用Foo2Genre创建n对m关系。

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; }
 }

我认为您需要包括流派。 这将与EF6中的一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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