【问题标题】:Automapper configuration between two types两种类型之间的 Automapper 配置
【发布时间】:2017-07-31 11:26:34
【问题描述】:

我有课(它的一部分):

Filter { string CashierId; }

还有

ClientQuery { IList<Person> Persons; }

Person 的样子:

    Person {
      SolvingPersonIn();
      SolvingPersonIn(string solvingPersonXnuc = null);

      string SolvingPersonXnuc { get; set; }

    }

以及如何配置 Automapper 以将我的 Filter 映射到 ClientQuery

类似这样的:

cashierId = "12345678";
ClientQuery.Persons should be one element with "12345678"

【问题讨论】:

  • Person 的哪个属性的值应为“12345678”?
  • SolvingPersonXnuc

标签: c# automapper


【解决方案1】:

Automapper 是一个对象-对象映射器,这意味着它将从一个对象转换为另一个对象。您可以在此线程example our to filtering a collection 中转换此类数据时应用过滤器:

Mapper.CreateMap<Customer, CustomerViewModel>()
    .ForMember(dest => dest.Orders, 
        opt => opt.MapFrom(src => src.Orders.Where(o => !o.DeletedDate.HasValue)));

例如,在您的情况下,您可以只取第一个,或者您事先测试您的数据,然后应用您的法线贴图。

 if (ClientQuery.Persons.Count(x => x.SolvingPersonXnuc) > 1)
 {
    // your logic here when you have more than one person with the CashierId
 }

 // apply your mapping here

你可以看一下官方文档,有很多例子Automapper documentation

【讨论】:

    【解决方案2】:

    如果您只想将单个 CashierId 添加到人员列表中,您可以创建并填充一个新列表:

    CreateMap<Filter, ClientQuery>
            .ForMember(dest => dest.Persons, 
                o => o.ResolveUsing(src => { 
                    return new List<Person> { new Person { SolvingPersonXnuc = src.CashierId }};
                })
            );
    

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      相关资源
      最近更新 更多