AutoMapper: Collection to Single string Property

后端 未结 1 1221
灰色年华
灰色年华 2020-12-11 17:21

I have a scenario in which I have to do following mapping

public class Company : BaseEntity
{            
    public         


        
相关标签:
1条回答
  • 2020-12-11 17:29

    You can use the following mapping:

    Mapper.CreateMap<Company, CompanyViewModel>()
        .ForMember(dest => dest.Services,
             m => m.MapFrom(src => string.Join(", ", src.CompanyServices
                                                        .Select (s => s.Service.Name))));
    

    But note that you won't be able to use the mapping in an IQueryable for LINQ to Entities directly, because EF will throw an exception that it can't convert the string.Join part into SQL. You'll have to use AsEnumerable and then do the mapping, like:

    Mapper.Map<T>(context.Entities.AsEnumerable(). ...)
    
    0 讨论(0)
提交回复
热议问题