2014-12-30 56 views
-2

所有記錄我有2個表:Linq to SQL |獲取其中一個外鍵不存在

Schools 
------- 
pk_school_id, 
title 

Business_Hours 
-------------- 
pk_id, 
fk_school_id 

我想pk_school_id和標題從學校表不存在由於fk_school_id所有pk_school_id在Business_Hours表中。

var Schools = (from b in Db.Language_School_Business_Hours 
    join s in Db.Language_Schools on b.fk_school_id equals s.pk_school_id into lrs 
    from lr in lrs.DefaultIfEmpty() 
    select new 
    { 
     LeftID = b.fk_school_id, 
     RightId = ((b.fk_school_id == lr.pk_school_id) ? lr.pk_school_id : 0) 
    }); 
+0

感謝您的編輯Andy! – vohrahul

回答

2

試試這個來實現自己的目標,不加入,只取未包含在Business_Hours表元素

var Schools = Db.Language_Schools 
    .Where(s => !Db.Language_School_Business_Hours 
    .Select(b => b.fk_school_id).ToList().Contains(s.pk_school_id)) 
    .Select(x => new 
    { 
     x.pk_school_id, 
     x.school_title 
    }); 
+0

這給了我一個內部服務器錯誤!我只會檢查一下這個有什麼問題! – vohrahul

+0

讓我知道如果你需要幫助,在這裏寫下服務器錯誤 – faby

+0

這給調試帶來以下錯誤。 base = {「查詢運算符'AsQueryable'不受支持。」} – vohrahul

1

我認爲我們可以一點點的第一.Select(...)後去除.ToList()簡化LINQ ,刪除最後的.Select(...)。請看下面的代碼。

var schools = Db.Language_Schools 
       .Where(w => !Db.Language_School_Business_Hours 
       .Select(s => s.fk_school_id) 
       .Contains(w.pk_school_id)) 
       .ToList();