2010-05-07 114 views
1

我有以下看法: -LINQ數查詢返回1,而不是0

CREATE VIEW tbl_adjudicator_result_view 
AS 
SELECT a.adjudicator_id, sar.section_adjudicator_role_id, s.section_id, sdr.section_dance_role_id, d.dance_id, c.contact_id, 
ro.round_id, r.result_id, c.title, c.first_name, c.last_name, d.name, r.value, ro.type 
FROM tbl_adjudicator a 
INNER JOIN tbl_section_adjudicator_role sar on sar.section_adjudicator_role2adjudicator = a.adjudicator_id 
INNER JOIN tbl_section s on sar.section_adjudicator_role2section = s.section_id 
INNER JOIN tbl_section_dance_role sdr on sdr.section_dance_role2section = s.section_id 
INNER JOIN tbl_dance d on sdr.section_dance_role2dance = d.dance_id 
INNER JOIN tbl_contact c on a.adjudicator2contact = c.contact_id 
INNER JOIN tbl_round ro on ro.round2section = s.section_id 
LEFT OUTER JOIN tbl_result r on r.result2adjudicator = a.adjudicator_id AND r.result2dance = d.dance_id 

當我直接對數據庫運行以下查詢我的數列中沒有結果

得到0
select adjudicator_id, first_name, COUNT(result_id) 
from tbl_adjudicator_result_view arv 
where arv.round_id = 16 
group by adjudicator_id, first_name 

然而,當我使用LINQ查詢我總是在計數列得1

var query = from arv in db.AdjudicatorResultViews 
        where arv.round_id == id 
        group arv by new { arv.adjudicator_id, arv.first_name} into grp 
        select new AdjudicatorResultViewGroupedByDance 
        { 
         AdjudicatorId = grp.Key.adjudicator_id, 
         FirstName = grp.Key.first_name, 
         Count = grp.Select(p => p.result_id).Distinct().Count() 
        }; 

什麼我需要改變查看/ Linq查詢。

回答

1

問題是:你正在將你的數據分組到LINQ查詢中 - 並且你總是會得到至少一個組。

該集團的Count可能是0 - 但羣體的數量將是1

2

你不是在做LINQ查詢同樣的事情,在SQL。 COUNT(result_id)不計算不同值result_id - 它計數非空值。

試試這個:

Count = grp.Select(p => p.result_id).Where(x => x != null).Count()