【发布时间】:2016-07-19 00:39:23
【问题描述】:
我正在关注这个答案AutoMapper mapping int[] or List<int> from ViewModel to a List<Type> in Domain Model 并已将它与UploadSongViewModel 上的CategoryId 绑定到SelectedCategoryIds,但是我还想让它在@987654327 上绑定SongId 到Id @。
namespace App
{
public static class AutoMapper
{
public static MapperConfiguration Config;
public static void Initialize()
{
//It works with CategoryId, but throws an error when I include SondId.
Config = new MapperConfiguration(x =>
{
x.CreateMap<int, SongCategory>()
.IgnoreAllNonExisting()
.ForMember(dest => dest.CategoryId, opt => opt.MapFrom(src => src))
.ForMember(dest => dest.SongId, opt => opt.MapFrom(src => src)); //Code that's throwing exception
x.CreateMap<UploadSongViewModel, Song>()
.IgnoreAllNonExisting()
.ForMember(dest => dest.AudioName, opt => opt.MapFrom(src => src.SongName))
.ForMember(dest => dest.AudioPath, opt => opt.MapFrom(src => src.SongPath))
.ForMember(dest => dest.SongCategories, opt => opt.MapFrom(src => src.SelectedCategoryIds))
.ForMember(dest => dest.SongCategories, opt => opt.MapFrom(src => src.Id)); //Code that's throwing exception
});
//Throws exception here because it can't bind SongId property
Config.AssertConfigurationIsValid();
}
}
}
public abstract class Entity
{
public int Id { get; set; }
}
public class SongCategory : Entity
{
public int SongId { get; set; }
public int CategoryId { get; set; }
}
public class Song : Audio
{
public string AlbumName { get; set; }
public string ArtistName { get; set; }
public List<SongCategory> SongCategories { get; set;}
}
public class UploadSongViewModel
{
public int Id { get; set; }
public string ArtistName { get; set; }
public string AlbumName { get; set; }
public int[] SelectedCategoryIds { get; set; }
public MultiSelectList CategoriesSelectList { get; set; }
}
我不太了解 Darin Dimitrov 回答中的自动映射器代码在做什么,因此很难调试。如果有人可以解释此映射如何适用于 categoryId 以及为什么它不适用于 SongId,那就太好了。
我得到的例外是:
System.Collections.Generic.List
1[[SoundVast.Models.SongCategory, SoundVast, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] cannot be mapped: SongCategories Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type System.Collections.Generic.List1[[SoundVast.Models.SongCategory, SoundVast, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 上的以下属性。 语境: 从 System.Int32 映射到属性 SongCategories 到 System.Collections.Generic.List`1[[SoundVast.Models.SongCategory, SoundVast, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 从 SoundVast.Areas.Upload.Models.UploadSongViewModel 类型映射到 SoundVast.Models.Song 引发了“AutoMapper.AutoMapperConfigurationException”类型的异常。
【问题讨论】:
标签: c# asp.net-mvc automapper