Reputation: 879
I have to show one row per one bill in my program, but one bill has more than 1 sub-bills. I would like to group information from 2 tables in one DataGridView. 1 row must show grouped info about all sub-bills. Only 2 columns are more complex than other: "Description" and "Sum". "Description" must contain all of descriptions of sub-bills and be delimited by new-line. I made it next way:
var documentQuery = (from doc in entities.Bas_DocumentData
select new
{
DocumentNum = doc.DocumentNum,
DocumentDate = doc.DocumentDate,
Description = doc.Bas_BonusData.Select(t => t.Description),
BillsCount = doc.Bas_BonusData.Count,
SupplierNum = doc.Bas_BonusData.Select(cred => cred.SupplierNum).FirstOrDefault(),
Debitor = doc.Bas_BonusData.Select(deb => deb.DebitorNum).FirstOrDefault(),
Manager = doc.Bas_BonusData.Select(manager => manager.ManagerName).FirstOrDefault(),
SupplierName = doc.Bas_BonusData.Select(supp => supp.SupplierName).FirstOrDefault(),
Sum = doc.Bas_BonusData.Sum(bill => bill.Price),
IsPrinted = doc.isPrinted,
IsSent = doc.isSent,
NotSummarize = doc.NotSummarize
}).OrderBy(key => key.DocumentNum)
.ToList()
.Select(q => new AcceptedBonusProjection
{
DocumentNum = q.DocumentNum,
DocumentDate = q.DocumentDate,
Description = String.Join("\n\r", q.Description.ToArray()),
BillsCount = q.BillsCount,
SupplierNum = q.SupplierNum,
Debitor = q.Debitor,
Manager = q.Manager,
SupplierName = q.SupplierName,
Sum = q.Sum,
IsPrinted = q.IsPrinted,
IsSent = q.IsSent,
NotSummarize = q.NotSummarize
});
Is there better way to achieve my goal? Which way can I shorten this query?
Upvotes: 2
Views: 364
Reputation: 52280
The first half (anony. struct) is not needed at all:
var documentQuery =
entities.Bas_DocumentData
.OrderBy(key => key.DocumentNum)
.Select(q => new AcceptedBonusProjection
{
DocumentNum = q.DocumentNum,
/* same as in your select snipped here as it does not add value */
NotSummarize = q.NotSummarize
})
.ToList();
Remark:
Please note that you do some subqueries that might not scale well (selecting from another table in your queries, for example doc.Bas_BonusData.Select(manager => manager.ManagerName).FirstOrDefault()
) - this will NOT be translated into a inner/outer-join and will result in many DB-queries. Eager loading will not solve this problem!
You should consider using a SQL-View/StoredProcedure/LINQ-Join Statements to change this.
Upvotes: 4