Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper .ForMember for collection

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 -> IEnumerable1 AttManager.Data.Request -> System.Collections.Generic.IEnumerable1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Destination path: RequestModel.Recipients.Recipients Source value: AttManager.Data.Request

like image 313
demo Avatar asked May 10 '16 16:05

demo


1 Answers

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.

like image 98
Arturo Menchaca Avatar answered Sep 27 '22 22:09

Arturo Menchaca