เรามีเอนทิตีเช่นนี้:
public class File{
public int Region{get;set;}
public bool ShowLocation{get;set;}
//Other fields are omitted
}
ฉันต้องการเขียนแบบสอบถามนี้:
SELECT Region,SUM(CASE WHEN ShowLocation=1 THEN 1 ELSE 0 END) AS
ShowCount,SUM(CASE WHEN ShowLocation=0 THEN 1 ELSE 0 END) AS NotShowCount
--WHERE omitted for the sake of simplicity
GROUP BY Region
ด้วยเหตุผลบางอย่าง ฉันต้องการใช้ Linq To Nhibernate (เรามีกลไกการกรองที่ซับซ้อนที่สร้าง Expression<Func<File,bool>>
)
จนถึงตอนนี้ฉันไม่พบวิธีใดในการบรรลุเป้าหมายนี้โดยใช้ Linq To NHibernate นี่คือความพยายามบางส่วนของฉัน:
Conditioanl Count:(ไม่มีข้อยกเว้น แต่จะนับทุกแถวอยู่แล้ว)
Files
.Where(whereExpression)
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
ShowCount=x.Count(f=>f.ShowLocation==1),
NotShowCount=x.Count(f=>f.ShowLocation==0)
});
ผลรวมตามเงื่อนไข: ไม่รองรับ/ยกเว้นการใช้งาน
Files
.Where(whereExpression)
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
ShowCount=x.SUM(f=>f.ShowLocation==1?1:0),
NotShowCount=x.SUM(f=>f.ShowLocation==0?1:0)
});
เลือกก่อนกลุ่ม: ไม่รองรับ/ยกเว้นการใช้งาน
Files.Where(whereExpression).Select(x=>new
{
x.Region,
Show=x.ShowLocation==1?1:0,
NotShow=x.ShowLocation==0?1:0
})
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
ShowCount=x.SUM(f=>f.Show),
NotShowCount=x.SUM(f=>f.NotShow)
});
UNION : ไม่รองรับ/ยกเว้นการใช้งาน
Files
.Where(whereExpression)
.Where(x=>x.ShowLocation==1)
.Select(x=>new
{
x.Region,
Show=1,NotShow=0
})
.Union(Files
.Where(whereExpression)
.Where(x=>x.ShowLocation==0)
.Select(x=>new
{x.Region,
Show=0,
NotShow=1
}))
.GroupBy(x=>x.Region)
.Select(x=>new
{
x.Region,
CountShow=x.Count(a=>a.Show),
CountNotShow=x.Count(a=>a.NotShow)
});
ฉันไม่มีเบาะแสอื่น ๆ มีความคิดอื่นอีกไหม?