![](/img/trans.png)
[英]Automapper If source is null, set destination object properties
[英]AutoMapper behaviour with readonly properties in source not being mapped to destination
我有一個配置,它執行反向映射以將源對象展開為目標對象,但是,如果源對象屬性是只讀的,它會被自動忽略,我必須手動映射它。
我的一些源對象有多達 100 個字段,創建這樣的手動映射感覺很麻煩,我不確定為什么自動映射器中存在這種行為。
有關我所描述的工作示例,請參閱下面的代碼片段。
using System;
using AutoMapper;
namespace automappertests
{
class Source
{
public int Field1Suffix1 { get; set; }
public int Field1Suffix2 { get; set; }
public int Field2Suffix1 { get; set; }
// !!Attention!!
// This is a readonly property with a private setter
public int Field2Suffix2 => Field2Suffix1;
}
class Destination
{
public Wrapper Field1 { get; set; }
public Wrapper Field2 { get; set; }
}
class Wrapper
{
public int Suffix1 { get; set; }
public int Suffix2 { get; set; }
public static Wrapper New(int suffix1, int suffix2) =>
new Wrapper
{
Suffix1 = suffix1,
Suffix2 = suffix2
};
}
class DestinationProfile : Profile
{
public DestinationProfile()
{
CreateMap<Destination, Source>()
.ReverseMap()
// !!Attention!!
// Why do I need to have an explicit ForMember MapFrom for the readonly property?
.ForMember(m => m.Field2, o => o.MapFrom(src => Wrapper.New(src.Field2Suffix1, src.Field2Suffix2)));
}
}
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg => { cfg.AddProfile<DestinationProfile>(); });
var mapper = config.CreateMapper();
var source = new Source()
{
Field1Suffix1 = 1,
Field1Suffix2 = 2,
Field2Suffix1 = 3,
};
var destination = mapper.Map<Source, Destination>(source);
Console.WriteLine($"Field1.Suffix1 = {destination.Field1.Suffix1}");
Console.WriteLine($"Field1.Suffix2 = {destination.Field1.Suffix2}");
Console.WriteLine($"Field2.Suffix1 = {destination.Field2.Suffix1}");
Console.WriteLine($"Field2.Suffix2 = {destination.Field2.Suffix2}");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
}
Output without .ForMember:
Field1.Suffix1 = 1
Field1.Suffix2 = 2
Field2.Suffix1 = 3
Field2.Suffix2 = 0
Output with .ForMember:
Field1.Suffix1 = 1
Field1.Suffix2 = 2
Field2.Suffix1 = 3
Field2.Suffix2 = 3
其實你沒有二傳手。 添加顯式私有 setter。
public int Field2Suffix2 { get => Field2Suffix1; private set => Field2Suffix1 = value; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.