【发布时间】:2017-02-02 15:15:09
【问题描述】:
我有一个父类:
public class Parent
{
...
public List<Location> Locations { get; set; }
}
位置类:
public class Location
{
public int LocationId { get; set; }
public string Name { get; set; }
}
映射的目标类:
public class Destination
{
...
public string DelimitedLocations { get; set; }
}
我需要使用 automapper 将 LocationId 列表从 Locations 映射到逗号分隔的字符串。
以下是我尝试过的几件事:
CreateMap<Parent, Destination>().ForMember(d => d.DelimitedLocations , o => o.MapFrom(s => string.Join(",", s.Locations.ToList().Select(t => t.LocationID.ToString()))))
结果: LINQ to Entities 无法识别方法 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' 方法,并且此方法无法转换为存储表达式。
下一次尝试:
CreateMap<Parent, Destination>()..ForMember(d => d.TestPlotLocationsSelected, o => o.MapFrom(s => s.TestPlotLocations.ToList().Select(t => string.Join(",", t.TestPlotLocationID.ToString()))))
结果: 类型“System.Collections.Generic.IEnumerable`1[System.String]”上不存在方法“ToString”。
不确定下一步该尝试什么。
【问题讨论】:
-
它与 AutoMapper 无关——不管有没有它,你都无法在 LINQ to Entities 查询中做你想做的事情。
-
在您的
DelimitedLocations的set;中,您可以尝试只创建一个StringBuilder和一个foreach并最终创建您想要的 - 这可能会容易得多.. -
感谢您的建议。我最终在映射之外填充了分隔属性。
标签: c# automapper