【问题标题】:Reusable functions/expressions in LINQ to Entities select clausesLINQ to Entities 选择子句中的可重用函数/表达式
【发布时间】:2015-10-20 21:51:10
【问题描述】:

我有很多代码可以将实体转换为类似于这样的数据传输对象:

var result = from t in DatabaseContext.SomeTable
             where t.Value1 = someValue
             select new SomeTableDTO()
             {
                  Value1 = t.Value1,
                  Value2 = t.Value2,
                  SomeParent = new SomeParentDTO()
                  {
                      Value3 = t.SomeParent.Value3,
                      Value4 = t.SomeParent.Value4
                  }
              };

这可行,但问题是我一遍又一遍地重复相同的代码,因为有许多 DTO 具有 SomeParent 属性。

var result = from t in DatabaseContext.SomeOtherTable
             where t.Value5 = someValue
             select new SomeOtherTableDTO()
             {
                  Value5 = t.Value5,
                  Value6 = t.Value6,
                  SomeParent = new SomeParentDTO()
                  {
                      Value3 = t.SomeParent.Value3,
                      Value4 = t.SomeParent.Value4
                  }
              };

我想做这样的事情,以便可以共享 SomeParentDTO 的转换:

var result = from t in DatabaseContext.SomeTable
             where t.Value1 = someValue
             select new SomeTableDTO()
             {
                  Value1 = t.Value1,
                  Value2 = t.Value2,
                  SomeParent = SomeParentConverter(t.SomeParent)
              };

.

Func<SomeParent, SomeParentDTO> SomeParentConverter = (parent) =>
{
    return new SomeParentDTO()
    {
        Value3 = parent.Value3,
        Value4 = parent.Value4
    };
};

但这当然行不通,因为 LINQ to Entities 不支持 InvokeThis posting 似乎朝着我想要的方向发展,但它使用了一个传递给 .Select()Expression,这并不能解决我的 DRY 问题。

有什么方法可以实现我想要的吗?

【问题讨论】:

    标签: c# linq-to-entities entity-framework-6


    【解决方案1】:

    您可以使用Automapper。支持IQueryable extensions中的映射。

    文档中的部分示例:

    public List<OrderLineDTO> GetLinesForOrder(int orderId)
    {
        Mapper.CreateMap<OrderLine, OrderLineDTO>()
            .ForMember(dto => dto.Item, conf => conf.MapFrom(ol => ol.Item.Name);
    
        using (var context = new orderEntities())
        {
            return context.OrderLines.Where(ol => ol.OrderId == orderId)
                        .Project().To<OrderLineDTO>().ToList();
        }
    }
    

    【讨论】:

    • 有趣,我以为 AutoMapper 只是尝试根据相似的属性名称进行匹配,我不知道它会影响 SQL 中最终选择的字段。我需要试试这个。
    猜你喜欢
    • 2018-02-20
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多