【问题标题】:How to map to add multiple IEnumerable<int> to an IEnumerable<int> property of a model如何映射以将多个 IEnumerable<int> 添加到模型的 IEnumerable<int> 属性
【发布时间】:2020-11-05 16:06:36
【问题描述】:

假设我有这个代码

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 执行此操作 stackoverflow.com/questions/12640881/… 或来自链接的副本 stackoverflow.com/questions/5284315/… ?
  • 但是我读你的问题越多,我就越不明白你想要做什么。请按原样提供示例数据以及所需的结果。您可以使用 JSON 表示
  • @CaiusJard 好的。现在编辑
  • 添加了预期结果
  • 所以你想让automapper做sample.Property1.Select(p1=&gt;new{p=p1,pt=ptype1}) .Concat(sample.Property2.Select(p2=&gt;new{p=p2,pt=ptype2})) .Concat(sample.Property3.Select(p3=&gt;new{p=p3,pt=ptype3})) .Select(new SampleModel{Id=pk,TypeId=ptype,Values=p})?

标签: c# .net linq automapper


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多