2010-01-13 81 views
1

參數所以我有一個查詢,看起來像這樣:Linq to SQL:使用int?在查詢

var clams = from clam in Clams 
      where clam.ClamTypeID == 143 && 
        clam.ParentClamID == null 
      select clam; 

沒有什麼太瘋狂了,返回我需要的結果。但是當我把它作爲一個int傳遞給可能的null值的函數時呢?我開始遇到問題。這裏是我的功能是什麼樣子:

public IQueryable<Clam> getAllClams(int clamTypeID, int? parentClamID) 
{ 
    return from clam in Clams 
      where clam.ClamTypeID == clamTypeID && 
        clam.ParentClamID == parentClamID 
      select clam; 
} 

該函數返回什麼 - 我查了PARAMS以確保它們是正確的,果然,parentClamID == NULL,仍然沒有結果。如果我改變clam.ParentClamID == parentClamID clam.ParentClamID == null它工作,所以我假設我使用int?不正確......任何想法是我在這裏做錯了嗎?

+0

下面是空類型,一般一個問題:http://stackoverflow.com/questions/586097/compare -nullable-types-in-linq-to-sql – 2010-01-13 17:03:40

+0

我喜歡你正在查詢蛤蜊。 – CBono 2012-12-11 22:11:39

回答

1

我以前有過這個問題。我找到工作的解決方法是這樣的:

public IQueryable<Clam> getAllClams(int clamTypeID, int? parentClamID) 
{ 
    return from clam in Clams 
      where clam.ClamTypeID == clamTypeID && 
        object.Equals(clam.ParentClamID, parentClamID) 
      select clam; 
} 
+0

耶,完全工作 - 謝謝! – onekidney 2010-01-13 17:15:00

0

試試這個:

public IQueryable<Clam> getAllClams(int clamTypeID, int? parentClamID) 
{ 
    var result = from clam in Clams where clam.ClamTypeID == clamTypeID select clam; 

     if(parentClamID.HasValue) result = result.Where(c => c.ParentClamID == parentClamID); 
     else result = result.Where(c => c.ParentClamID == null); 

     return from clam in result select clam; 
} 
2
public IQueryable<Clam> getAllClams(int clamTypeID, int? parentClamID) 
{ 
    return from clam in Clams 
      where clam.ClamTypeID == clamTypeID && 
        clam.ParentClamID == parentClamID.HasValue ? parentClamID.Value : null 
      select clam; 
} 
+0

很好,謝謝! – onekidney 2010-01-13 17:59:57