AutoMapper: collection in a single-line property

I have a script in which I have to do the following mapping

public class Company : BaseEntity { public string Name { get; set; } public virtual ICollection<CompanyService> CompanyServices { get; set; } } public class Service : BaseEntity { public string Name { get; set; } public virtual ICollection<CompanyService> CompanyServices { get; set; } } public class CompanyService : BaseEntity { public long CompanyID { get; set; } public virtual Company Company { get; set; } public long ServiceID { get; set; } public virtual Service Service { get; set; } } 

And the corresponding models to view

 public class CompanyViewModel : BaseEntity { public string Name { get; set; } public string Services { get; set; } } public class ServiceViewModel : BaseEntity { public string Name { get; set; } } public class CompanyServiceViewModel : BaseEntity { public string ServiceName { get; set; } } 

I want to use Map using AutoMapper, in which I have to get the service name as a comma-separated string in the CompanyViewModel class

 Mapper.CreateMap<Company, CompanyViewModel>(); 
+6
source share
1 answer

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 cannot directly use the mapping in IQueryable for LINQ to Entities, because EF throws an exception that cannot convert part of string.Join to SQL. You will need to use AsEnumerable , and then do the mapping, for example:

 Mapper.Map<T>(context.Entities.AsEnumerable(). ...) 
+9
source

Source: https://habr.com/ru/post/969721/


All Articles