两种类型之间的自动配置

时间:2017-07-31 11:26:35

标签: c# automapper

我有课(它的一部分):

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"

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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