1

如何将以下 sql 查询转换为 lambda 表达式?

select cg.Code, ci.ChangeType, SUM(oc.Value) from OtherCharges oc 
left join changeitems ci on oc.ChangeItemKey = ci.ChangeItemKey
left join ChangeGroups cg on ci.ChangeGroupKey = cg.ChangeGroupKey
where OtherKey = 'AB235A00-FEB2-4C4F-B0F9-3239FD127A8F'
group by cg.Code, ci.ChangeType
order by cg.Code, ci.ChangeType
4

1 回答 1

2

假设您的表已经有 .NET 域类型:

IQueryable<OtherCharges> otherCharges = ...
Guid otherKey = ...

var query = otherCharges.Where(oc => oc.OtherKey == otherKey)
    .Select(oc => new { oc.ChangeItem, oc.Value })
    .GroupBy(t => new { t.ChangeItem.ChangeGroup.Code, t.ChangeItem.ChangeType })
    .OrderBy(g => g.Key.Code)
    .ThenBy(g => g.Key.ChangeType)
    // note that if Code is a non-nullable type you'll want to cast it to int? at some
    // point so that when pulled into memory EF won't complain that you can't cast
    // null to a non-nullable type. I expect that Code could sometimes be null here
    // do to your use of LEFT OUTER JOIN in the T-SQL
    .Select(g => new { g.Key.Code, g.Key.ChangeType, Sum = g.Sum(t => t.Value) });

var inMemoryResult = query.ToList();

请注意,我在这里使用的是 OtherCharge.ChangeItem 和 ChangeItem.ChangeGroup。这些是关联属性,需要作为模型的一部分进行设置(例如,首先对 EF 代码使用流畅的配置)。

于 2012-09-16T20:33:47.357 回答