我需要一个可以在创建匿名类型时调用的可重用函数。
我尝试了以下内容,但是从EntityFramework转换函数到表达式时出错。
任何人都可以帮助我。
var query2 = (from parts in cabinetOrderParts
join header in headers
on parts.SQLHeaderID equals header.SQLHeaderID
join order in orders
on parts.SQLOrderID equals order.SQLOrderID
where parts.SQLHeaderID == sqlheaderid
orderby parts.SQLOrderID
orderby parts.CabinetDoorPartsID
select new
{
Height = doit.GetHeight(parts, order),
//a number of other parts, header and order fields omitted.
});
public static class doit
{
public static Expression<Func<ICabinetDoorPart, ISQLOrder, decimal?>> GetHeight(ICabinetDoorPart part, ISQLOrder order)
{
//parts.CutToHeight.HasValue ? parts.CutToHeight : parts.Height
Expression condition = Expression.Condition(
Expression.Constant(part.CutToHeight.HasValue), Expression.Constant(part.CutToHeight), Expression.Constant(part.Height));
var selector = Expression.Lambda<Func<ICabinetDoorPart, ISQLOrder, decimal?>>(condition);
return selector.Compile();
}
}
更新: 我使用了Debugview并捕获了实体框架正在使用的表达式。
.Lambda #Lambda10<System.Func`2[<>f__AnonymousType1`2[<>f__AnonymousType0`2[Interfaces .Shiloh.ICabinetDoorPart,Interfaces.SQLFilePro.ISQLHeader],Interfaces.SQLFilePro.ISQLOrder],<>f__AnonymousType2`1[System.Nullable`1[System.Decimal]]]> (<>f__AnonymousType1`2[<>f__AnonymousType0`2[Interfaces.Shiloh.ICabinetDoorPar t,Interfaces.SQLFilePro.ISQLHeader],Interfaces.SQLFilePro.ISQLOrder] $<>h__TransparentIdentifier1)
{
.New <>f__AnonymousType2`1[System.Nullable`1[System.Decimal]](.If (
((($<>h__TransparentIdentifier1.<>h__TransparentIdentifier0).parts).CutToHeight).HasValue
) {
(($<>h__TransparentIdentifier1.<>h__TransparentIdentifier0).parts).CutToHeight
} .Else {
(($<>h__TransparentIdentifier1.<>h__TransparentIdentifier0).parts).Height
})
}
我认为这与c#
相似public static Expression<Func<object[], decimal?>> GetHeight(object[] value)
{
var exp = Expression.New(new { Height = new decimal?() }.GetType().GetConstructors()[0],
Expression.Constant(10));
var selector = Expression.Lambda<Func<object[], decimal?>>(exp);
return selector;
}
但仍然没有快乐!