繁体   English   中英

如何映射添加多个IEnumerable<int> 到一个 IEnumerable<int> 模型的属性

[英]How to map to add multiple IEnumerable<int> to an IEnumerable<int> property of a model

假设我有这个代码

int? pk=100;
int? ptype1 =51;
int? ptype2 =52;
int? ptype3 =53;

public class SampleDto
{
    public IEnumerable<int> Property1{ get; set; }
    public IEnumerable<int> Property2{ get; set; }
    public IEnumerable<int> Property3{ get; set; }
}

SampleDto sample = new SampleDto();
sample.Property1.Add(11);
sample.Property1.Add(12);
sample.Property1.Add(13);
sample.Property2.Add(21);
sample.Property2.Add(22);
sample.Property2.Add(23);
sample.Property3.Add(31);
sample.Property3.Add(32);
sample.Property3.Add(33);

如何使用 Automapper 映射 SampleDto 属性以添加到 SampleModel 的 IEnumerable

public class SampleModel
{
    public int? Id { get; set; } //same for all pk 
    public int? TypeId { get; set; } //ptype depending on the property. Ex. ptype1 for Property1
    public int? Values { get; set; } //Value of Property
}

有了上面的值,我想要一个带有以下数据的 SampleModel IEnumerable 的预期结果:

Id =100, TypeId =51, Values =11
Id =100, TypeId =51, Values =12
Id =100, TypeId =51, Values =13
Id =100, TypeId =52, Values =21
Id =100, TypeId =52, Values =22
Id =100, TypeId =52, Values =23
Id =100, TypeId =53, Values =31
Id =100, TypeId =53, Values =32
Id =100, TypeId =53, Values =33

AutoMapper 是错误的工作工具,因为您没有进行一对一映射(SampleDto 和 SampleModel 之间没有共同的“根”)。

但是,使用 LINQ,您可以创建一个相当简单的转换函数,将SampleModel对象列表转换为SampleDto对象的相应列表。 像这样的东西:

static IEnumerable<SampleDto> ConvertFunction(IEnumerable<SampleModel> sample)
{
    var query = from d in sample
                group d by d.Id into g
                let lookup = g.ToLookup(x => x.TypeId, x => x.Values)
                select new SampleDto
                {
                    Property1 = lookup[51],
                    Property2 = lookup[52],
                    Property3 = lookup[53]
                };
    return query.ToList();
}

然后,如果您绝对必须,您可以将其与自定义转换功能集成到 automapper 中:

var config = new MapperConfiguration(cfg =>
        cfg.CreateMap<IEnumerable<SampleModel>, IEnumerable<SampleDto>>()
        .ConvertUsing(input => ConvertFunction(input))
    );

这允许您执行以下操作:

var mapper = new Mapper(config);
var result = mapper.Map<IEnumerable<SampleDto>>(sample);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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