2017-09-14 44 views
0

我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的屬性類型爲字符串類型的集合

這在異常結束:

System.InvalidOperationException:'沒有泛型方法'ToList'類型 'System.Linq.Enumerable'與提供的類型 兼容發言:。如果 方法是非通用的,則不應提供類型參數。 「

如果我試試這個來代替:

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關係。

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

你可以發佈你的'Foo'和'BarDTO'類嗎? –

+0

是的,發佈一切。也刪除ToList,最有可能不需要。 –

回答

1

我認爲你需要包含流派。這將在EF6中起作用。