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

时间:2012-09-14 00:47:19

标签: sql linq

如何将以下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

1 个答案:

答案 0 :(得分: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代码的流畅配置)。