我有一种情况,在这种情况下,我必须执行以下映射
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 模型
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>();
最佳答案
您可以使用以下映射:
Mapper.CreateMap<Company, CompanyViewModel>()
.ForMember(dest => dest.Services,
m => m.MapFrom(src => string.Join(", ", src.CompanyServices
.Select (s => s.Service.Name))));
但是请注意,您将无法直接使用
IQueryable
中的LINQ到Entities的映射,因为EF会抛出一个异常,即它无法将string.Join
部分转换为SQL。您必须使用AsEnumerable
,然后执行映射,例如:Mapper.Map<T>(context.Entities.AsEnumerable(). ...)
关于AutoMapper:收集到单字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23816068/