2013-04-01 85 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 
             }; 

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