Automapper v5 升级后为空 属性 值

Empty property value after Automapper v5 upgrade

我有以下代码在 Automapper 的 v3 中有效,但在 v5 中不再有效。 更新 它也适用于 v4。

CallScheduleProfile 在其构造函数中将 Title 属性 设置为 class 的实例,该实例将 true 的值传递给它。

CallScheduleProfileViewModel 在其构造函数中将 Title 属性 设置为另一个 class 的实例,该实例传递值 true"Title".

我已经在 AutoMapper 中为所有 4 个 classes 设置了映射,然后我调用了 Map。

结果是 CallScheduleProfileViewModel 上的 Title 属性 有一个布尔值 trueFriendlyName 是空的,即使它是在其构造函数中设置。

我认为正在发生的事情是 CallScheduleProfileViewModel 上的构造函数被调用并且 FriendlyName 被分配但是当映射发生时它调用 Entry 上的构造函数然后映射 UxEntry 上存在的任何属性并将其分配给 Title 属性,默认情况下 FriendlyName 将为空,因为 FriendlyName 不存在UxEntry 其值未被复制。

我的假设可能是错误的,但无论哪种方式,我如何在映射中填充 FriendlyName

Update :我在嵌套类型上查看了 Automapper documentation,文档中提供的代码也存在这个问题。如果我将字符串 属性 添加到 InnerDest 并在 OuterDest 构造函数中设置它的值,在 Map 之后它的值为空。

public static void Main(string[] args)
{
    Mapper.Initialize(cfg =>
    {
        cfg.CreateMap<UxEntry<bool>, Entry<bool>>();

        cfg.CreateMap<CallScheduleProfile, CallScheduleProfileViewModel>();
    });

    var old = new CallScheduleProfile();

    var newmodel = Mapper.Map<CallScheduleProfile, CallScheduleProfileViewModel>(old);

    Console.WriteLine(newmodel.Title.Value);
    Console.WriteLine(newmodel.Title.FriendlyName);
}

public class UxEntry<T>
{
    public static implicit operator T(UxEntry<T> o)
    {
        return o.Value;
    }

    public UxEntry()
    {
        this.Value = default(T);
    }

    public UxEntry(T value)
    {
        this.Value = value;
    }

    public T Value { get; set; }
}


public class CallScheduleProfile
{
    public CallScheduleProfile()
    {
        this.Title = new UxEntry<bool>(true);
    }

    public UxEntry<bool> Title { get; set; }

}

public class Entry<T>
{
    public Entry()
    {
    }

    public Entry(T value, string friendlyName)
    {
        this.Value = value;
        this.FriendlyName = friendlyName;
    }

    public T Value { get; set; }
    public string FriendlyName { get; set; }

    public static implicit operator T(Entry<T> o)
    {
        return o.Value;
    }
}


public class CallScheduleProfileViewModel 
{
    public CallScheduleProfileViewModel()

    {
        this.Title = new Entry<bool>(true, "Title");
    }
    public Entry<bool> Title { get; set; }
}

嗯,Automapper 将这个 属性 映射到 null 因为:

A) 类型 Entry<T> 的构造函数将此 属性 设置为 null

B) Automapper 在调用 CallScheduleProfileViewModel 中的构造函数后(!)创建 Entry<T> 的新实例。

C) 没有为 Automapper 设置其他规则

您在这里可以做的是更改配置,以便让 Automapper 知道其中一个属性应该使用默认值:

        Mapper.Initialize(cfg =>
        {
            // when UxEntry is mapped to Entry value "Title" is used for property FriendlyName
            cfg.CreateMap<UxEntry<bool>, Entry<bool>>()
                .ForMember(dest => dest.FriendlyName, opt => opt.UseValue("Title"));

            cfg.CreateMap<CallScheduleProfile, CallScheduleProfileViewModel>();
        });

现在我们可以从 CallScheduleProfileViewModel.

中的构造函数中删除多余的 属性 初始化

运行 您的代码没有其他更改会产生以下输出:

true    
Title