2013-04-01 84 views
0

我是表達式樹新手,不知道如何實現以下內容。將感謝任何想法或鏈接。擴展表達式樹

我有2個實體需要映射到相應的視圖模型。我希望映射器是獨立的表達式,可以在我的應用程序的variuos部分中重用。

這映射表達式是MainEntity轉換爲MainEntityViewModel:

public static Expression<Func<MainEntity, MainEntityViewModel>> MainMapper = 
    me => new MainEntityViewModel() 
     { 
      Property1 = me.Property1, // direct mapping 
      OtherEntityModel = new OtherEntityViewModel() // here i'd like to use outer expression 
       { 
        Name = me.OtherEntityObject.Name, 
        Description = me.OtherEntityObject.Description 
       } 
     }; 

我也想我OtherEntity是一個獨立的表達是這樣的:

public static Expression<Func<OtherEntity, OtherEntityViewModel>> OtherMapper = 
    oe => new OtherEntityViewModel() 
     { 
      Name = oe.Name, 
      Description = oe.Description 
     }; 

但我沒有想法如何應用它在第一個映射器內部。我想我需要以某種方式擴展第一棵樹(添加表達式節點或其他),但不知道該怎麼做。
謝謝!
PS:我知道AutoMapper等,但想使用手動映射。

+0

你會被重建AutoMapper。但它是開源的,那麼爲什麼不看一下?也許你可以借鑑一些想法(並給予適當的信貸)。此外,我不認爲有人會爲你寫表達式樹。至少要展示一些起點。 –

+0

嗨格特,感謝您的回覆。我沒有要求完整的解決方案,只是想知道一些一般原則,關鍵字或鏈接,將導致我的答案。目前我對錶情樹並不熟悉。我是對的,我需要處理底層表達式樹,只是添加一個新節點? – LINQ2Vodka

+0

不幸的是,我無法使AutoMapper能夠處理需要大量映射(嵌套列表,轉換/鑄件,展平)的複雜對象,並且必須將其轉換爲IQueriable作爲結果。它給出了各種未處理的錯誤。 – LINQ2Vodka

回答

0

試試這個:

public static Func<MainEntity, OtherEntity, Func<OtherEntity, OtherEntityViewModel>, MainEntityViewModel> 
       MainMapper = me, oe, oMapper => new MainEntityViewModel() 
                { 
                 Property1 = me.Property1, // direct mapping 
                 OtherEntityModel = oMapper.Invoke(oe) 
                }; 


public static Func<OtherEntity, OtherEntityViewModel> 
       OtherMapper = oe => new OtherEntityViewModel() 
             { 
              Name = oe.Name, 
              Description = oe.Description 
             }; 

我不明白爲什麼你需要使用表達式,但你可以把它放回去,如果你想