[英]How to map my complex type use AutoMapper?
我在使用AutoMapper時遇到一些問題。 有人可以為我解釋如何創建地圖嗎? 不要擔心很多代碼塊。 這是非常簡單的邏輯,我只是不明白映射器是如何工作的...謝謝您的幫助。 AutoMapperConfig:
private void MappingApiInputSubscription(IMapperConfigurationExpression expression)
{
expression.CreateMap<ApiInputSubscription, Subscription>()
.ForMember(
dest => dest.SearchRequest,
opt => opt.MapFrom(src =>src.SearchRequest));
}
ApiSearchRequest:
public class ApiSearchRequest
{
public string Text { get; set; }
public int? CategoryId { get; set; }
public bool PriceRequired { get; set; }
public int? MinPrice { get; set; }
public int? MaxPrice { get; set; }
public int? CurrencyId { get; set; }
public DateTime? PublishDateFrom { get; set; }
public DateTime? PublishDateTo { get; set; }
public DateTime? EventDateFrom { get; set; }
public DateTime? EventDateTo { get; set; }
public bool PhotoAttached { get; set; }
public int? OwnerId { get; set; }
public ICollection<int> Offices { get; set; }
}
我的ApiInputSubscription模型:
[Serializable]
public class ApiInputSubscription
{
public string SubscriptionName { get; set; }
public ApiSearchRequest SearchRequest { get; set; }
}
我的訂閱模型:
public class Subscription : ISubscription
{
public int Id { get; set; }
public int OwnerId { get; set; }
public string SubscriptionName { get; set; }
public SearchRequest SearchRequest { get; set; }
public ISubscription WithOwner(IUser user)
{
user = user ?? throw new ArgumentNullException(nameof(user), "subscription owner can't be null!");
var clone = (Subscription)MemberwiseClone();
clone.OwnerId = user.Id;
return clone;
}
}
SearchRequest類別:
public class SearchRequest : ISearchRequest
{
public string Text { get; set; }
public int? CategoryId { get; set; }
public bool PriceRequired { get; set; }
public int? MinPrice { get; set; }
public int? MaxPrice { get; set; }
public int? CurrencyId { get; set; }
public DateTime? PublishDateFrom { get; set; }
public DateTime? PublishDateTo { get; set; }
public bool EventDateRequired { get; set; }
public DateTime? EventDateFrom { get; set; }
public DateTime? EventDateTo { get; set; }
public bool PhotoAttached { get; set; }
public int PostsOnPage { get; set; } = 10;
public PostStatus Status { get; set; }
public SortPostsBy SortPostsOrder { get; set; }
public bool OnlyInappropriate { get; set; }
public int? OwnerId { get; set; }
public int Skip { get; set; }
public ICollection<int> Offices { get; set; }
}
首先,您需要告訴AutoMapper如何將ApiSearchRequest映射到SearchRequest,其次要忽略所有其他屬性:
private void MappingApiInputSubscription(IMapperConfigurationExpression expression)
{
expression.CreateMap<ApiSearchRequest, SearchRequest>()
// add other properties as required
.ForMember(dest => dest.PostsOnPage, opt => opt.Ignore());
expression.CreateMap<ApiInputSubscription, Subscription>()
.ForMember(
dest => dest.SearchRequest,
opt => opt.MapFrom(src => src.SearchRequest))
.ForAllOtherMembers(dest => dest.Ignore());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.