我一直遇到这种类型的错误,但仅限于编辑用例。 类型' AutoMapper.AutoMapperMappingException'的例外情况发生在AutoMapper.dll中但未在用户代码中处理附加信息:缺少类型映射配置或不支持的映射。
控制器编辑方法:
public ActionResult Edit(int? id)
{
var o = m.TrackGetById(id.GetValueOrDefault());
if (o == null)
{
return HttpNotFound();
}
else
{
var editForm = AutoMapper.Mapper.Map<TrackBase, TrackEditForm>(o); // i get the exception HERE
return View(editForm);
}
}
Manager TrackEditInfo方法:
public TrackBase TrackEditInfo(TrackEditForm newItem)
{
var o = ds.Tracks.Find(newItem.Id);
if (o == null)
{
return null;
}
else
{
ds.Entry(o).CurrentValues.SetValues(newItem);
ds.SaveChanges();
return Mapper.Map<Track, TrackBase>(o);
}
}
追踪视图模型:
public class TrackBase
{
[Key]
public int Id { get; set; }
[Display(Name = "Track Name")]
[Required, StringLength(150)]
public string Name { get; set; }
[Required, StringLength(150)]
public string Clerk { get; set; }
[StringLength(150)]
[Display(Name = "Composer Names")]
public string Composers { get; set; }
[Required]
public string Genre { get; set; }
public IEnumerable<int> AlbumIds { get; set; }
}
public class TrackAdd : TrackBase
{
public HttpPostedFileBase ClipUpload { get; set; }
}
public class TrackAddForm : TrackBase
{
public SelectList GenreList { get; set; }
[Required]
[Display(Name = "Clip Upload")]
[DataType(DataType.Upload)]
public string ClipUpload { get; set; }
}
public class TrackWithDetail : TrackBase
{
public TrackWithDetail()
{
Albums = new List<AlbumBase>();
}
[Display(Name = "Album Name")]
public ICollection<AlbumBase> Albums { get; set; }
public string AlbumName()
{
var album = this.Albums.FirstOrDefault();
if (album == null)
{
return "-";
}
return album.Name;
}
[Display(Name = "Sample Clip")]
public string ClipUrl
{
get
{
return $"/clip/{Id}";
}
}
}
public class TrackClip
{
public int Id { get; set; }
public string ClipContentType { get; set; }
public byte[] Clip { get; set; }
}
public class TrackEditForm
{
public TrackEditForm() { }
[Key]
public int Id { get; set; }
[Display(Name = "Track Name")]
[Required, StringLength(150)]
public string Name { get; set; }
[StringLength(150)]
[Display(Name = "Composer Names")]
public string Composers { get; set; }
}
AutoMapper:
cfg.CreateMap<Models.RegisterViewModel, Models.RegisterViewModelForm>();
// Tracks
cfg.CreateMap<Models.Track, Controllers.TrackBase>();
cfg.CreateMap<Models.Track, Controllers.TrackWithDetail>();
cfg.CreateMap<Models.Track, Controllers.TrackClip>();
cfg.CreateMap<Controllers.TrackAdd, Models.Track>();
cfg.CreateMap<Controllers.TrackAddForm, Models.Track>(); //ok
cfg.CreateMap<Controllers.TrackBase, Controllers.TrackEditForm>();
});