I have entity Request
and model RequestModel
public class RequestModel : BaseModel
{
public IEnumerable <int> Recipients { get; set; }
}
public class Request : IIdent
{
public virtual ICollection <RequestComment> Comments { get; set; }
}
public class RequestComment : IIdent
{
[ForeignKey("User")]
public int? UserId { get; set; }
}
I want to create mapping for Recipients
CreateMap<Request, RequestModel>()
.ForMember(d => d.Recipients, o => o.MapFrom(s => s.Comments.Select(x => x.UserId )))
But I get exception :
AutoMapper.AutoMapperMappingException was caught _HResult=-2146233088 HResult=-2146233088 IsTransient=false Message= Mapping types: Request -> IEnumerable
1 AttManager.Data.Request -> System.Collections.Generic.IEnumerable
1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Destination path: RequestModel.Recipients.Recipients Source value: AttManager.Data.Request
The problem comes when you try to convert an IEnumerable<RequestComment>
to IEnumerable<int>
, so Automapper is going to try to find an conversion between RequestComment
to int
, but is not defined.
You can define the conversion from RequestComment
to int
like this:
.CreateMap<RequestComment, int>().ConvertUsing(rm => rm.UserId ?? 0);
And the map between the requests models:
.CreateMap<Request, RequestModel>()
.ForMember(d => d.Recipients, o => o.MapFrom(s => s.Comments))
Also, another way to solve your problem is defining an AfterMap
operation:
.CreateMap<Request, RequestModel>()
.AfterMap((r, rm) => rm.Recipients = new List<int>(r.Comments.Select(c => c.UserId ?? 0)));
I just add ?? 0
because UserId
type is int?
, so need to be converted to int
for Recipients
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With