将实体框架集合映射到逗号分隔的字符串与automapper

时间:2017-02-02 15:15:10

标签: c# 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; }
}

我需要使用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无法识别方法&#39; System.String Join(System.String,System.Collections.Generic.IEnumerable`1 [System.String])&#39;方法,并且此方法无法转换为商店表达式。

下一次尝试:

CreateMap<Parent, Destination>()..ForMember(d => d.TestPlotLocationsSelected, o => o.MapFrom(s => s.TestPlotLocations.ToList().Select(t => string.Join(",", t.TestPlotLocationID.ToString()))))

结果: 没有方法&#39; ToString&#39;存在于&#39; System.Collections.Generic.IEnumerable`1 [System.String]&#39;中。

不确定接下来要尝试什么。

1 个答案:

答案 0 :(得分:1)

Select语句应该类似于

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; }
}

结果

enter image description here