You are trying to run subqueries inside a larger query. Even in SQL that is a bad idea. Performance will be awful. I believe the correct approach here is to use grouping since you only seem to care about 2 fields in your dataset. Maybe I'm missing something here but it seems like your query is going to return back a single object for each row in your AllBN_Dam
collection but every row will have the same value and it appears that the results would be for the single row so I'd expect most counts to be 1. Additionally you're using bitwise and (&) and I assume you meant logical and (&&).
I'm wondering here if you actually just want 1 result that is a summary for the specific system ID(?) I'm breaking the query up so it is easier to understand.
var group = from p in db.AllBN_Dam
where p.SystemId == 1 && p.ToDate == yesterday()
group p by new { TransactionType = p.TransactionTypeId, Kind = p.ElhKind_HvKind } into g
select new { TransactionType = g.Key.TransactionType, Kind = g.Key.Kind, ItemCount = g.Count(), TotalAmount = g.Sum(x => x.Amount) };
//To simplify the expression, create temp variables to filter data
var bnItems = group.Where(x => x.TransactionType == 1 && x.Kind == 0);
var exteraItems = group.Where(x => x.TransactionType == 1 && x.Kind == 212);
var reverseItems = group.Where(x => x.TransactionType == 1 && x.Kind == 213);
var damageItems = group.Where(x => x.TransactionType == 2);
//One record for all rows
var result = new SmsTypeV2() {
BNCnt = bnItems.Max(x => x.ItemCount),
BNAmount = bnItems.Sum(x => x.TotalAmount),
ExteraCnt = exteraItems.Max(x => x.ItemCount),
ExteraAmount = exteraItems.Sum(x => x.TotalAmount),
ReverseCnt = reverseItems.Max(x => x.ItemCount),
ReverseAmount = reverseItems.Sum(x => x.TotalAmount),
DamageAmount = damageItems.Sum(x => x.TotalAmount),
};