dest.ShirtColor, dest =-6ren">
gpt4 book ai didi

automapper - 为什么我在使用 Condition 时会收到 "Nullable object must have a value"异常?

转载 作者:行者123 更新时间:2023-12-02 07:05:06 25 4
gpt4 key购买 nike

在下面的示例代码中,我得到一个“可空对象必须有一个值”。为什么我需要以下修复来完成这项工作:

.ForMember(dest => dest.ShirtColor,
dest => dest.MapFrom(src => src.ShirtColor != null
? new OptionSetValue((int) src.ShirtColor)
: null))

AutoMapper.Mapper.CreateMap<PersonA, PersonB>()
.ForMember(dest => dest.FirstName, dest => dest.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LastName, dest => dest.MapFrom(src => src.LastName))

// Condition to avoid overwriting existing data!!!
.ForMember(dest => dest.ShirtColor,
dest => dest.Condition(src => src.ShirtColor != null))
.ForMember(dest => dest.ShirtColor,
dest => dest.MapFrom(
src => new OptionSetValue((int)src.ShirtColor)))
// Fix that should not be needed due to condition:
//.ForMember(dest => dest.ShirtColor,
// dest => dest.MapFrom(
// src => src.ShirtColor != null
// ? new OptionSetValue((int) src.ShirtColor)
// : null));


PersonA source = new PersonA();
source.FirstName = "Thomas";
source.LastName = "Jefferson";
source.ShirtColor = null; // nullable int

PersonB destination = new PersonB();
destination.FirstName = "Thomas";
destination.LastName = "Jefferson";
destination.ShirtColor = new OptionSetValue(4);

// Results in: "Nullable object must have a value" despite the fact that
// condition should have been met!
Mapper.Map<PersonA, PersonB>(source, destination);

Debug.Assert(destination.ShirtColor != null);
Console.WriteLine("Our existing data was not overwritten!!");

Console.WriteLine("Hit enter to exit");
Console.ReadLine();

下面是如何定义 OptionSet:
公共(public)类 OptionSetValue
{
公共(public) OptionSetValue(){}

    public OptionSetValue(int value)
{
Number = value;
}

public int Number { get; set; }
}

最佳答案

只需使用 PreCondition而不是 Condition ..

所以改变你的

//Condition to avoid overwriting existing data!!!
.ForMember(dest => dest.ShirtColor, dest => dest.Condition(src => src.ShirtColor != null))
.ForMember(dest => dest.ShirtColor, dest => dest.MapFrom(src => new OptionSetValue((int)src.ShirtColor)))



//Condition to avoid overwriting existing data!!!
.ForMember(dest => dest.ShirtColor, dest => dest.PreCondition(src => src.ShirtColor != null))
.ForMember(dest => dest.ShirtColor, dest => dest.MapFrom(src => new OptionSetValue((int)src.ShirtColor)))

关于automapper - 为什么我在使用 Condition 时会收到 "Nullable object must have a value"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13692533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com