简体   繁体   English

如何设置匹配属性名称为字符串集合的配置约定?

[英]How to set configuration convention of matching property name is a string collection?

I have two models: 我有两个模型:

public class UserModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string NetId { get; set; }
    public string Email { get; set; }
    public string Departments { get; set; }
    public string Titles { get; set; }
}


public class UserReport : Entity
{
    public string Name { get; set; }
    public string NetId { get; set; }
    public string Email { get; set; }
    public List<string> Departments { get; set; }
    public List<string> Titles { get; set; }
}

And as such I can write my automapper mapping like this: 因此,我可以这样编写我的自动映射器映射:

CreateMap<UserReport, UserModel>()
            .ForMember(x => x.Departments, x => x.MapFrom(y => string.Join("\n", y.Departments)))
            .ForMember(x => x.Titles, x => x.MapFrom(y => string.Join("\n", y.Titles)));

However, I don't want to do this for every instance of this, because this approach is going to be used on pretty much every POCO to DTO conversion. 但是,我不想在每个实例中都这样做,因为这种方法几乎将用于每个POCO到DTO的转换。 Is there a way I can write a convention in the config to check if the destination property name is of type string and it matches a property on the source type of list<string> to do the string join? 有没有一种方法可以在配置中编写约定,以检查目标属性名称是否为字符串类型,并且与源类型list<string>上的属性匹配以进行字符串连接?

Mappings can nest so you just define an additional map for List<string> to string : 映射可以嵌套,因此您只需为List<string>string定义一个附加映射:

CreateMap<List<string>, string>().ConvertUsing(strings => {
    if (strings != null)
      return string.Join("\n", strings);
    return "";
});

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

相关问题 枚举和匹配属性的C#命名约定 - C# naming convention for enum and matching property AutoMapper:设置成员名称匹配约定 - AutoMapper: setup member name matching convention 如何从ConfigurationElementCollection中获取配置属性名称 - How to get the configuration property name out of a ConfigurationElementCollection 如何查询与某个过滤器匹配的集合属性中的任何项目的实体? - How to query for entities with any item in a collection property matching a certain filter? 如何通过属性名称访问自定义集合属性 - How to access a custom collection property by its property name 如何为集合中对象的特定属性设置属性更改事件 - How to set Property Changed Event for a Particular Property of an Object in Collection 如何在列表上设置DefaultValueAttribute <Color> 集合属性(设置默认颜色)? - How to set DefaultValueAttribute on List<Color> collection property (set default colors)? 如何获得与 model 的命名策略匹配的 JSON 属性名称? - How to get a JSON property name matching the naming strategy for a model? 如何通过属性名称字符串使用动态从Com互操作对象获取/设置值 - how to get/set value from Com interop object using dynamic by property name string 通用集合中的this [string name] - this[string name] in Generic Collection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM