[英]C# - Automapper with Custom Type Conversion
我正在嘗試向域 map 請求 object,我可以閱讀英語,但我絕對無法在 automapper 文檔中找到解決方案。
問題:
How can I map the ContainedEvent object from source to a derived class in destination object based on the EventType attribute in ContainedEvent object, because Event is an abstract class. So let's say EventType == 1 in the source object, then Event attribute should be converted到它的派生類之一。 我也不想 map null 屬性,但我處理了。
這是請求 object
public class CreatePostRequest
{
public long EventTime { get; set; }
public List<IFormFile>? Pictures { get; set; }
public ContainedEvent Event { get; set; }
public virtual List<string>? Tags { get; set; }
}
public class ContainedEvent
{
public string Description { get; set; }
#nullable enable
public string? Requirements { get; set; }
public int? Slots { get; set; }
public double? EntrancePrice { get; set; }
public int EventType { get; set; }
}
這是域 object
public class Post
{
public int Id { get; set; }
public DateTime EventTime { get; set; }
public Location Location { get; set; }
public int LocationId { get; set; }
public AppUser User { get; set; }
public string UserId { get; set; }
public Event Event { get; set; }
public int EventId { get; set; }
#nullable enable
public IEnumerable<string>? Pictures { get; set; }
#nullable enable
public virtual List<PostTags>? Tags { get; set; }
}
public abstract class Event
{
public int Id { get; set; }
public string Description{ get; set; }
public string? Requirements { get; set; }
public Post? Post { get; set; }
}
這就是我所堅持的..
public class RequestToDomainProfile : Profile
{
public RequestToDomainProfile()
{
CreateMap<CreatePostRequest, Post>()
.ForAllMembers(opt => opt.Condition((src, dest, srcMember) => srcMember != null));
}
}
這個想法是將所有 Event 實現存儲在 context.Items 中,並在映射中提供一個選擇器。
沒有測試過,但應該是這樣的
當您創建 map 時:
CreateMap<CreatePostRequest, Post>()
.ForMember(x => x.Event, opt => opt.MapFrom((src, dest, destMember, context) =>
{
if(src.Event.EventType == 1)
{
return context.Items["EventImplementation1"];
}
if(src.Event.EventType == 2)
{
return context.Items["EventImplementation2"];
}
// ...
}));
當你 map 你的 object:
Post p = _mapper.Map<CreatePostRequest, Post>(postRequest, opts =>
{
opts.Items["EventImplementation1"] = new YourFirstEventImplementation();
opts.Items["EventImplementation2"] = new YourSecondEventImplementation();
// ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.