Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper: Collection to Single string Property

Tags:

automapper

I have a scenario in which I have to do 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 corresponding View Models

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 Map using AutoMapper in which I should get Service's Name as comma separated string in CompanyViewModel class

Mapper.CreateMap<Company, CompanyViewModel>();
like image 602
Mohsan Avatar asked May 22 '14 20:05

Mohsan


1 Answers

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(). ...)
like image 92
Gert Arnold Avatar answered Sep 28 '22 01:09

Gert Arnold