【问题标题】:Extending expression tree扩展表达式树
【发布时间】:2013-04-01 02:43:56
【问题描述】:

我是表达式树的新手,不知道如何实现以下内容。将感谢任何想法或链接。

我有 2 个实体需要映射到相应的视图模型。我希望映射器成为独立的表达式,可以在我的应用程序的各个部分中重用。

这个映射器表达式是将 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 等,但想使用手动映射。

【问题讨论】:

  • 您将重建 AutoMapper。但它是开源的,为什么不看看呢?也许您可以借用一些想法(并给予应有的信任)。此外,我认为没有人会为您编写表达式树。至少显示一些起点。
  • 嗨格特,感谢您的回复。我不是要求完整的解决方案,只是想知道一些一般原则、关键字或链接,它们将引导我找到答案。我目前不熟悉表达式树。我是否需要处理底层表达式树并添加一个新节点?
  • 不幸的是,我无法使 AutoMapper 用于需要大量映射(嵌套列表、转换/转换、展平)的复杂对象,因此必须将其转换为 IQueriable。它给出了各种未处理的错误。

标签: c# linq entity-framework lambda expression


【解决方案1】:

试试这个:

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
                                        };

我不太清楚你为什么需要使用 Expression,但如果你愿意,你可以把它放回去

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多