繁体   English   中英

使用自动映射器将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM