我必须在我的程序中每一个帐单显示一行,但是一个帐单有超过1个子帐单。我想在一个DataGridView中分组来自2个表的信息。 1行必须显示有关所有子账单的分组信息。 只有2列比其他列更复杂:“描述”和“总和”。 “描述”必须包含子账单的所有描述,并由新线分隔。我接下来做了:
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
});
有没有更好的方法来实现我的目标?我可以通过哪种方式缩短此查询?
答案 0 :(得分:4)
根本不需要上半部分(anony.struct):
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();
<强>注:强>
请注意,您执行的某些子查询可能无法很好地扩展(从查询中的另一个表中进行选择,例如doc.Bas_BonusData.Select(manager => manager.ManagerName).FirstOrDefault()
) - 这不会被转换为内部/外部联接,并将导致许多数据库查询。急切的加载不会解决这个问题!
您应该考虑使用SQL-View / StoredProcedure / LINQ-Join语句来更改它。