![](/img/trans.png)
[英]How to map Integer to String with AutoMapper 3 and Entity Framework
[英]Map Entity Framework collection to comma delimted string with automapper
我有一個家長班:
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; }
}
我需要使用自動映射器將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'。
不知道下一步該怎么做。
選擇語句應類似於
o.Locations.Select(x => x.LocationId).ToList()
public class Program
{
public static void Main()
{
Initialize();
var source = new Parent
{
Locations = new List<Location>
{
new Location {LocationId = 1, Name = "One"},
new Location {LocationId = 2, Name = "Two"},
new Location {LocationId = 3, Name = "Three"},
}
};
var destination = Mapper.Map<Parent, Destination>(source);
Console.ReadLine();
}
public static void Initialize()
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Parent, Destination>()
.ForMember(dest => dest.DelimitedLocations, mo => mo.MapFrom(src =>
src.Locations != null
? string.Join(",", src.Locations.Select(x => x.LocationId).ToList())
: ""));
});
Mapper = MapperConfiguration.CreateMapper();
}
public static IMapper Mapper { get; private set; }
public static MapperConfiguration MapperConfiguration { get; private set; }
}
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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.