1

How to convert the following sql query to lambda expression?

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 Answer 1

2

Assuming you already have .NET domain types for your tables:

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();

Note that I'm using OtherCharge.ChangeItem and ChangeItem.ChangeGroup here. These are association properties and need to be set up as part of your model (e. g. using fluent configuration for EF code first).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.