我有一些会计应用程序允许创建文档并添加一些位置(行/行)。 这是控制器获取特定文档的那些行:
public JsonResult GetIncDocDetails(long id, int pagesize, int pagenum)
{
var dbResult = db.fooIncDocDetail.Where(d => d.DocumentID == id).Where(d => d.RecordStatusID != 2).Include(f => f.fooFood).
OrderBy(d => d.Date).
Select(s => new
{
s.IncDocDetailID,
s.FoodID,
s.MeasureUnit,
s.Amount,
s.Price,
s.VATRate,
s.Excise,
s.DocumentID,
s.UserID,
s.RecordDate,
s.RecordStatusID,
s.Date,
s.FoodName,
s.DetailNumber,
fooFoodName = s.fooFood.Name
}).Skip(pagesize * pagenum).Take(pagesize);
return Json(dbResult, JsonRequestBehavior.AllowGet);
}
所以我希望通过这个控制器获得更多信息,例如:
此特定文档的所有行的总和:
Summa = db.fooIncDocDetail.Where(d => d.DocumentID == id).
Where(d => d.RecordStatusID == 1).
Sum(a => (decimal?)(a.Amount* a.Price)) ?? 0;
此特定文档的所有行的总计数:
Total = db.fooIncDocDetail.Where(d => d.DocumentID == id).
Where(d => d.RecordStatusID != 2)
.Count()
此特定文件的属性:
Document = db.fooDocument.Where(d => d.DocumentID == id).
Select(d => new
{
d.DocumentID,
d.DocDate,
d.RegNumber,
d.UserID,
d.RecordDate,
d.RecordStatusID,
d.RegistrationDate,
d.Number,
d.Description,
d.ObjectID,
d.DocumentTypeID,
d.ContragentName,
DocumentTypeName = d.fooDocumentType.Name
})
但是我如何才能在一个LINQ查询中组合所有这些,我首先写的?感谢
答案 0 :(得分:1)
基本上,您可以将所有详细信息查询嵌入到最后一个查询Select
中,方法是将它们投影到匿名或特定创建类型的属性中,因此原始的(1)和(2)成为(3)的子查询。只需更改d
变量以避免冲突,例如:
// The original query. Must be declared here and put into variable
// to avoid exception due to `Skip` / `Take` subquery processing EF bug
// It still will be executed as part of the other query
var details = ...;
var result = db.fooDocument
.Where(d => d.DocumentID == id).
.Select(doc => new
{
Document = new
{
doc.DocumentID,
doc.DocDate,
doc.RegNumber,
doc.UserID,
doc.RecordDate,
doc.RecordStatusID,
doc.RegistrationDate,
doc.Number,
doc.Description,
doc.ObjectID,
doc.DocumentTypeID,
doc.ContragentName,
DocumentTypeName = doc.fooDocumentType.Name
},
Summa = ...,
Total = ...,
Details = details
})
.FirstOrDefault();