gpt4 book ai didi

c# - Automapper:如何不重复从复杂类型到基类的映射配置

转载 作者:行者123 更新时间:2023-11-30 22:01:56 24 4
gpt4 key购买 nike

我有一堆继承自 CardBase 的 DTO 类:

// base class
public class CardBase
{
public int TransId {get; set; }
public string UserId { get; set; }
public int Shift { get; set; }
}

// one of the concrete classes
public class SetNewCardSettings : CardBase
{
// specific properties ...
}

在我的 MVC 项目中,我有一堆具有 AuditVm 复杂类型的 View 模型,它们具有与 CardBase 相同的属性:

public class AuditVm
{
public int TransId {get; set; }
public string UserId { get; set; }
public int Shift { get; set; }
}

public class CreateCardVm : CardVm
{
// specific properties here ...

public AuditVm Audit { get; set }
}

那些 View 模型不能从 AuditVm 继承,因为它们中的每一个都已经有一个父级。我想我可以像下面这样设置我的映射,这样我就不必为每个具有 AuditVm 的 View 模型指定从 AuditVmCardBase 的映射> 作为复杂类型。但它不起作用。如何正确地将复杂类型映射到具有基类属性的展平类型?

  Mapper.CreateMap<AuditorVm, CardBase>()
.Include<AuditorVm, SetNewCardSettings>();

// this does not work because it ignores my properties that I map in the second mapping
// if I delete the ignore it says my config is not valid
Mapper.CreateMap<AuditorVm, SetNewCardSettings>()
.ForMember(dest => dest.Temp, opt => opt.Ignore())
.ForMember(dest => dest.Time, opt => opt.Ignore());

Mapper.CreateMap<CreateCardVm, SetNewCardSettings>()
// this gives me an error
.ForMember(dest => dest, opt => opt.MapFrom(src => Mapper.Map<AuditorVm, SetNewCardSettings>(src.Auditor)));

// I also tried this and it works, but it does not map my specific properties on SetNewCardSettings
//.ConvertUsing(dest => Mapper.Map<AuditorVm, SetNewCardSettings>(dest.Auditor));

更新:这是 fiddle https://dotnetfiddle.net/iccpE0

最佳答案

.Include 用于非常具体的情况——您有两个结构相同的类层次结构,您想要映射,例如:

public class AEntity : Entity { }

public class BEntity : Entity { }

public class AViewModel : ViewModel { }

public class BViewModel : ViewModel { }

Mapper.CreateMap<Entity, ViewModel>()
.Include<AEntity, AViewModel>()
.Include<BEntity, BViewModel>();

// Then map AEntity and BEntity as well.

所以除非你有这种情况,否则 .Include 不是正确的使用方法。

我认为最好的选择是使用 ConstructUsing:

 Mapper.CreateMap<AuditVm, CardBase>();

Mapper.CreateMap<AuditVm, SetNewCardSettings>()
.ConstructUsing(src =>
{
SetNewCardSettings settings = new SetNewCardSettings();
Mapper.Map<AuditVm, CardBase>(src, settings);
return settings;
})
.IgnoreUnmappedProperties();

Mapper.CreateMap<CreateCardVm, SetNewCardSettings>()
.ConstructUsing(src => Mapper.Map<SetNewCardSettings>(src.Audit))
.IgnoreUnmappedProperties();

我还合并了 this answer's忽略所有未映射属性的扩展方法。由于我们正在使用 ConstructUsing,因此 AutoMapper 不知道我们已经处理了这些属性。

更新的 fiddle : https://dotnetfiddle.net/6ZfZ3z

关于c# - Automapper:如何不重复从复杂类型到基类的映射配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27317719/

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