0

我可以使用以下代码将一组相同类型的集合映射到单个集合。

AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
                dest => dest.Drivers,
                opt => opt.MapFrom(src => src.BikeDrivers.Concat(src.CarDrivers).Concat(src.TruckDrivers))); 

通过上述解决方案,我可以将所有三种类型的驱动程序映射到一个集合中。我的目标对象(驱动程序)有一个名为 DriverType 的属性,它有助于识别驱动程序的类型。(自行车司机/汽车司机/卡车司机)

在上面的代码中,我如何根据我添加的集合设置 DriverType 属性。

例如:我必须硬编码

DriverType = CarDriver 用于 CarDrivers 集合项 DriverType = BikeDriver 用于 BikeDrivers 集合项。

提前致谢

4

1 回答 1

1

要设置 DriverType 属性,您必须在源对象中具备此知识。我看不到你的大图,但这可能用作样本

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var s = new Source()
                        {
                            BikeDrivers = new List<BikeDriver>() {new BikeDriver()},
                            CarDrivers = new List<CarDriver>() {new CarDriver()},
                            TruckDrivers = new List<TruckDriver>() {new TruckDriver()},
                        };

            var d = new Destination();


            AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
                dest => dest.Drivers,
                opt => opt.MapFrom(src => src.BikeDrivers.Concat<IDriver>(src.CarDrivers).Concat<IDriver>(src.TruckDrivers)));

            var result = AutoMapper.Mapper.Map(s, d);
        }

        public class Driver : IDriver
        {
            public string DriverType { get; set; }
        }

        public class Destination
        {
            public IEnumerable<IDriver> Drivers { get; set; }
        }

        public class Source
        {
            public IEnumerable<BikeDriver> BikeDrivers { get; set; }
            public IEnumerable<CarDriver> CarDrivers { get; set; }
            public IEnumerable<TruckDriver> TruckDrivers { get; set; }
        }

        public interface IDriver
        {
            string DriverType { get; set; }
        }

        public class BikeDriver : IDriver
        {
            public string DriverType
            {
                get { return "BikeDriver"; }
                set { throw new NotImplementedException(); }
            }
        }
        public class CarDriver : IDriver
        {
            public string DriverType
            {
                get { return "CarDriver"; }
                set { throw new NotImplementedException(); }
            }
        }
        public class TruckDriver : IDriver
        {
            public string DriverType
            {
                get { return "TruckDriver"; }
                set { throw new NotImplementedException(); }
            }
        }
    }
}
于 2012-06-03T10:44:31.340 回答