gpt4 book ai didi

c# - 定义子类型映射时,新版本的 Automapper 抛出转换异常

转载 作者:行者123 更新时间:2023-11-30 21:55:10 24 4
gpt4 key购买 nike

假设我有一个源类和两个目标类,一个更通用,一个更具体(继承自更通用的类):

public class Source
{
public int A { get; set; }
public string Str { get; set; }
}

public class DestinationBase
{
public int A { get; set; }
}

public class DestinationDerived : DestinationBase
{
public string Str { get; set; }
}

对于 Automapper 3.*,此代码完美运行:

    Mapper.Initialize(cfg => {
cfg.CreateMap<Source, DestinationBase>();
cfg.CreateMap<Source, DestinationDerived>()
.IncludeBase<Source, DestinationBase>();
});

var src = new Source() { A = 1, Str = "foo" };
var dest = new DestinationBase();

Mapper.Map(src, dest);

但是升级到4.0.4后,这个映射抛出异常:

System.InvalidCastException: Unable to cast object of type 'DestinationBase' to type 'DestinationDerived'

我做错了什么或者这是 AutoMapper 中的错误?

.net fiddle中的代码:

最佳答案

看起来在 4.x 中您不再需要显式包含 base。以下工作正常并按预期将 a 输出为 1。

Mapper.Initialize(cfg => {
cfg.CreateMap<Source, DestinationBase>();
cfg.CreateMap<Source, DestinationDerived>();
});

var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationBase();

Mapper.Map(src, dest);

Console.WriteLine("dest.a: " + dest.a);

同样,映射到 DestinationDerived 也可以正确映射从 base 继承的属性:

var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationDerived();

Mapper.Map(src, dest);

Console.WriteLine("dest.a: " + dest.a);

关于c# - 定义子类型映射时,新版本的 Automapper 抛出转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32507051/

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