我有一个场景,我必须做以下的映射
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>();
答案 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(). ...)