簡體   English   中英

Automapper map 從屬性到類

[英]Automapper map from properties to classes

我在將具有屬性的簡單 class 轉換為具有屬性的 class 時遇到問題,這些屬性本身也是稱為ProductDataField的類

 public class ProductDataField
    {
      
        public string Value { get; set; }

        public string Name{ get; set; }
    }

資源:

     public class ProductDetailsViewModel 
     {
        public CultureInfo Language { get; set; }

        public string SeoTitle { get; set; }

        public string SeoDescription { get; set; }

        public string SeoKeywords { get; set; }

        public string ProductFamily { get; set; }
     }

目的地:

    public class DetailsComplexViewModel 
    {
        public ProductDataField Language { get; set; }

        public ProductDataField SeoTitle { get; set; }

        public ProductDataField SeoDescription { get; set; }

        public ProductDataField SeoKeywords { get; set; }

        public ProductDataField ProductFamily { get; set; }
   }

我正在嘗試 map 將 ProductDataField 中的“Name”屬性轉換為“ProductDetailsViewModel”中的屬性名稱,並將“Value”屬性轉換為該屬性的值。

我試過用 CreateMap 映射它們,但我總是遇到類似的錯誤

“表達式 'x => x.ProductFamily.Value' 必須解析為頂級成員,而不是任何子對象的屬性”

任何幫助將不勝感激

這並不是 AM 的真正用途,也許只使用反射會更好,但可以做到:)

CreateMap<object, ProductDataField>().ConvertUsing((s,_, c)=>new ProductDataField { Value = s as string, Name = (string) c.Items["member"] });
CreateMap<ProductDetailsViewModel, DetailsComplexViewModel>().ForAllMembers(o=>o.PreCondition((ResolutionContext c)=>(c.Items["member"] = o.DestinationMember.Name) != null));

Map調用:

Map<DetailsComplexViewModel>(new ProductDetailsViewModel { SeoTitle = "title", SeoDescription = "descr" }, _=>{} )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM