2012-09-14 182 views
1

如何將下列sql查詢轉換爲lambda表達式?將以下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 

回答

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代碼的流暢配置)。

相關問題