简体   繁体   English

自动映射器使用目标属性并映射单个属性

[英]Automapper use destination properties and map single property

I want to use automapper to map between 2 lists. 我想使用自动映射器在2个列表之间进行映射。 One list contains a code and a string, the other contains the code and other fields. 一个列表包含一个代码和一个字符串,另一个包含代码和其他字段。 I want to use all the existing values/properties on the destination object, except for one. 我想使用目标对象上所有现有的值/属性,除了一个。 Is this possible with automapper? automapper有可能吗? I don't want to specify all the properties with a UseDestinationValue(). 我不想使用UseDestinationValue()指定所有属性。 Tried the following but instead of returning my destination list with the one property updated, it returns a new list with only matching items (in both lists) and all the fields are null: 尝试了以下操作,但是它没有返回更新了一个属性的目标列表,而是返回了一个仅包含匹配项的新列表(在两个列表中),并且所有字段均为空:

public static IMappingExpression<TSource, TDest> UseAllDestinationValues<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
    {
        expression.ForAllMembers(opt => opt.UseDestinationValue());
        return expression;
    }

    Mapper.CreateMap<Perm, PermViewModel>()
            .UseAllDestinationValues()
            .ForMember(dest => dest.CanEdit, opt => opt.MapFrom(s => s.editable));

var items = Mapper.Map<List<Perm>, List<PermViewModel>>(list, model.Items.Items);

I had to do something sort of similar using nullable doubles from one application to another. 我必须使用从一个应用程序到另一个应用程序的可为空的double来做类似的事情。 You could set up a type converter. 您可以设置一个类型转换器。 Without your specific classes I can't speak to exactly how to do this, but here is my example. 没有您的特定班级,我无法确切地说出该如何做,但这是我的示例。

Mapper.CreateMap<double?, double>().ConvertUsing<NullableDoubleConverter>();

private class NullableDoubleConverter : TypeConverter<double?, double>
{
    protected override double ConvertCore(double? source)
    {
        if (source == null)
            return Constants.NullDouble;
        else
            return (double)source;
    }
}

You could obviously adapt this using something like. 您显然可以使用类似的方法对此进行调整。

Mapper.CreateMap<Perm, PermViewModel>().ConvertUsing<PermConverter>();

private class PermConverter : TypeConverter<Perm, PermViewModel>
{
    protected override PermViewModel ConvertCore(Perm source)
    {
        return new PermViewModel() 
        {
             //Set your parameters here. 
        };
    }
}

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

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