![](/img/trans.png)
[英]Should I use two “where” clauses or “&&” in my LINQ query?
[英]How should I correctly compose my Linq query where the condition is set to a foreign entity
以下是用於解釋此問題的示例數據:
tblPrimary
1, John, 2011-01-03T11:12:00z
2, John, 2011-02-04T10:54:12z
tblDetail:
1, 1, 14, Dept01
2, 1, 12, Dept02
3, 2, 10, Dept03
4, 2, 17, Dept04
使用上面的示例表,給了一個“名稱”,在這里我需要返回與tblPrimary.Name中的名稱關聯的每個詳細記錄。 tblPrimary.Name不是唯一的,因此會有重復項,但是它們實際上是不同的訂單項,因為它們具有不同的日期和時間。
使用SQLMetal,將生成代碼,以便該對象處理兩個表之間的關系。 牢記這一點,我按如下方式構造查詢:
var q = from i in dbcontext.tblDetail
where i.tblPrimary.Name == 'John' && i.PrimaryId == i.tblPrimary.PrimaryId
select i;
使用上面的示例數據,如果我在tblPrimary中有兩個“ John”,並且具有不同的DateAdded,並且在每個tbJohn中的tblDetail中有2條記錄,則查詢返回的結果是:
John - 2011-01-03T11:12:00z
1, 1, 14, Dept01
2, 1, 12, Dept02
3, 2, 10, Dept03
4, 2, 17, Dept04
John - 2011-02-04T10:54:12z
1, 1, 14, Dept01
2, 1, 12, Dept02
3, 2, 10, Dept03
4, 2, 17, Dept04
我真正想要的結果是:
John - 2011-01-03T11:12:00z
1, 1, 14, Dept01
2, 1, 12, Dept02
John - 2011-02-04T10:54:12z
3, 2, 10, Dept03
4, 2, 17, Dept04
誰能建議我不使用Joins來解決此Linq查詢的方法? 我假設兩個表之間的sqlmetal生成關系應該已經為我處理了聯接。
嗯,看一下查詢的這一部分:
i.PrimaryId == i.tblPrimary.PrimaryId
以這樣的方式定義tblPrimary屬性,使得該表達式始終為真。
誰能建議我不使用Joins來解決此Linq查詢的方法?
這個怎么樣?
var q =
from i in dbcontext.tblDetail
let j = i.tblPrimary
select new {Detail = i, Primary = j};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.