AutoMapper:收集到单字符串属性 [英] AutoMapper: Collection to Single string Property

查看:120
本文介绍了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; }    
}

以及相应的视图模型

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的名称

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>();

推荐答案

您可以使用以下映射:

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然后进行映射,例如:

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(). ...)

这篇关于AutoMapper:收集到单字符串属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆