AutoMapper:收集到单字符串属性

标签 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 模型

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/

相关文章:

c# - 如何根据运行时条件忽略属性?

c# - 如何获取 OData 可查询 Web API 端点过滤器并将其映射到 DTO 对象?

automapper - Automapper:dto对象的自动 map 收集属性

.net-core - 如何从不同的程序集在 Automapper 中注册配置文件?

c# - 带有 Unity 的 Automapper - 在哪里放置 CreateMap 的东西?

c# - 取消映射源属性时强制抛出异常

c# - 使用 MVC3 中的存储库模式和 Entity Framework 将域模型转换为 ViewModel 并再次返回

unit-testing - 如何干净地对自定义 ValueResolver ResolveCore(...) 方法进行单元测试

asp.net-mvc - 带有自动映射器的抽象类

unit-testing - 如何对使用 AutoMapper ProjectTo 的代码进行单元测试?