LINQ to Entities中的可重用函数/表达式选择子句

时间:2015-10-20 21:51:10

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

我有很多代码将实体强制转换为与此类似的数据传输对象:

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似乎正朝着我想要的方向前进,但是使用了传递给Expression的单.Select(),这并不能解决我的DRY问题。

有什么方法可以达到我的目的吗?

1 个答案:

答案 0 :(得分:0)

您可以使用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();
    }
}