AutoMapper:集合到单个字符串属性

时间:2014-05-22 20:02:04

标签: automapper

我有一个场景,我必须做以下的映射

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; }    
}

以及相应的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; }
}

我想使用AutoMapper进行映射,其中我应该在CompanyViewModel类中将Service的名称作为逗号分隔的字符串

Mapper.CreateMap<Company, CompanyViewModel>();

1 个答案:

答案 0 :(得分:11)

您可以使用以下映射:

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

但是请注意,您将无法直接在IQueryable中使用LINQ to Entities中的映射,因为EF会抛出一个异常,它无法将string.Join部分转换为SQL 。您必须使用AsEnumerable然后执行映射,例如:

Mapper.Map<T>(context.Entities.AsEnumerable(). ...)