【问题标题】:AutoMapper: Collection to Single string PropertyAutoMapper:集合到单个字符串属性
【发布时间】:2014-05-22 20:02:04
【问题描述】:

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

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 类中以逗号分隔的字符串形式获取服务名称

Mapper.CreateMap<Company, CompanyViewModel>();

【问题讨论】:

    标签: automapper


    【解决方案1】:

    您可以使用以下映射:

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

    【讨论】:

    • 这个答案对我有帮助。但是你有一个例子来说明你对 AsEnumerable 的意思吗?我已经遇到过它不适用于 IQueryable
    • 非常有帮助的 tks
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多