我對 Automapper 有點陌生,所以我可能會嘗試將它用于不應該用于的事情,但它就在這里。我有兩節課:
public class Container
{
public int Id { get; set; }
public string Code { get; set; }
public string StrVal { get; set; }
public DateTime Date { get; set; }
public Containee Containee { get; set; }
}
public class Containee
{
public int Id { get; set; }
public decimal Value { get; set; }
public string DifferentStr { get; set; }
public DateTime birthday { get; set; }
}
我有一個看起來像這樣的 DTO:
public class ContaineeDTO
{
public int Id { get; set; }
public decimal Value { get; set; }
public string DifferentStr { get; set; }
public DateTime birthday { get; set; }
public string Code { get; set; }
}
我想要做的是使用 Automapper 將我的 Container 映射到我的 ContaineeDTO。我覺得這應該使用決議器,特別是用于將代碼從容器傳遞到容器 DTO,但我不確定如何繼續,任何幫助將不勝感激。
uj5u.com熱心網友回復:
您可以將此配置放在Startup.cs:
var config = new MapperConfiguration(
cfg => cfg.CreateMap<Container, ContaineeDTO>()
.ForMember(containeeDto => containeeDto.Value, opt =>
opt.MapFrom(container => container.Containee.Value))
.ForMember(containeeDto => containeeDto.DifferentStr, opt =>
opt.MapFrom(container => container.Containee.DifferentStr))
.ForMember(containeeDto => containeeDto.birthday, opt =>
opt.MapFrom(container => container.Containee.birthday));
重要說明:您在兩個類中命名了相同的屬性,因此沒有必要在映射定義中提供它們的名稱(如您所見,我沒有這樣做)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487108.html
