[英]Automapper - exclude some objects from mapped collection
我有以下地圖規則:
CreateMap<ViewModels.ApplicationDriverAccidentFormVM, ApplicationDriverAccidentDomain>();
然后我想將 ViewModels.ApplicationDriverFormVM 映射到 ApplicationDriverDomain,兩者都有 Accidents 屬性,它們是每種類型的適當集合。
public class ApplicationDriverDomain
{
public List<ApplicationDriverAccidentDomain> Accidents { get; set; }
}
public class ApplicationDriverFormVM
{
public List<ApplicationDriverAccidentFormVM> Accidents { get; set; }
}
我想排除(不映射)所有不滿足某些條件的記錄我嘗試編寫以下代碼:
CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>()
.ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => GetNotNullFromCollection(src.Accidents)))
其中 GetNotNullFromCollection 是:
List<object> GetNotNullFromCollection(object input)
{
List<object> output = new List<object>();
foreach (var item in (List<object>)input)
{
if (!Utils.IsAllNull(item))
output.Add(item);
}
return output;
}
但它說我:
無法將類型為“System.Collections.Generic.List
1[Web.ViewModels.ApplicationDriverAccidentFormVM]' to type 'System.Collections.Generic.List
1[System.Object]”。
為什么以及如何做?
您的方法GetNotNullFromCollection
接收一個對象,但您正在向它傳遞一個列表。 無論如何,我建議使用泛型而不是對象。
我通過以下方式解決了它:
CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>().ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => src.Accidents.Where(o => !Utils.IsAllNull(o))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.