gpt4 book ai didi

c# - 从双映射

转载 作者:行者123 更新时间:2023-11-30 12:56:46 28 4
gpt4 key购买 nike

我正在尝试使用 Automapper 5.0.2.0 将类型 A 映射到类型 B:

public class TypeA
{
public double Length { get; set; }
}


public class TypeB
{
public Distance Length { get; set; }
}

我假设长度以英寸为单位存储并创建了这个映射配置文件:

public class CalculationProfile : Profile
{
public CalculationProfile()
{
CreateMap<TypeA, TypeB>()
.ForMember(dest => dest.Length,
opt => opt.MapFrom(src => new Distance(src.Length, "Inch")))
}
}

我这样使用它:

Mapper.Initialize(configuration =>
{
configuration.AddProfile(new CalculationProfile());
});

var typeA = new TypeA(){Length = 1.0};

var typeB = Mapper.Map<TypeB>(typeA);

但是最后一行抛出以下错误:

AutoMapper.AutoMapperMappingException was unhandled by user code
HResult=-2146233088
Message=Missing type map configuration or unsupported mapping.

Mapping types:
Double -> Distance
System.Double -> UnitClassLibrary.DistanceUnit.Distance
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
at lambda_method(Closure , Double , Distance , ResolutionContext )
at lambda_method(Closure , Object , Object , ResolutionContext )
at TestProject.AutoMapperTests.FromPersistenceObjectToCalculationModel_Test() in C:\...\AutoMapperTests.cs:line 69
InnerException:

对于 Automapper 来说,这似乎是一个非常简单的案例,但我似乎无法修复错误。任何建议表示赞赏。

最佳答案

你真的想要在 double 和 distance 之间进行新的类型转换:

CreateMap<double, Distance>().ConvertUsing(src => new Distance(src, "Inch"));

关于c# - 从双映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38597989/

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