我在一個asp.net mvc應用程序中使用帶有edmx文件和POCO的實體框架4。可爲空的可選參數
首先,我有一個人類被映射到數據庫中的表。
public class Person
{
public Int32 ID{get;set;}
public string Name{get;set;}
public Int32? ParentID{get;set;}
}
然後在我的服務層,我有以下功能檢索所有人。如果一個的parentID供給檢索將與的parentID的那些的人數:
public List<Person> Get(int? parentPersonID = null)
{
var persons = Repository().GetAll(c => c.ParentID == parentPersonID);
}
最後,庫()函數返回一個IRepository<Person>
,其包含方法:
public IQueryable<TModel> GetAll(Expression<Func<TModel, bool>> predicate = null)
{
var result = ObjectSet.AsQuaryable(); //ObjectSet is a ObjectSet<Person> instance
if (predicate != null)
result = result.Where(predicate);
return result;
}
現在,問題是如果我將null作爲parentPersonID傳遞給服務層,則爲Get(null)
。枚舉不會產生任何結果。但是,如果我將服務層代碼修改爲:
public List<Person> Get(int? parentPersonID = null)
{
var persons = Repository().GetAll(null);
}
一切正常。
任何想法是爲什麼?
編輯: 如果我更換服務層功能代碼:
var persons = Repository().GetAll(c => c.ParentID.Equals(parentPersonID));
代替:
var persons = Repository().GetAll(c => c.ParentID == parentPersonID);
它按預期工作 - 第一行從數據庫,而檢索記錄第二個不是。 我仍然好奇在這種情況下,Equals()
和==
有什麼不同。
你的假設是正確的,是的。此外,明確的檢查工作(與Equals()相同的結果)。我很好奇,但是如何處理與null值相等的變量。後來還發現了這一個:http://stackoverflow.com/questions/682429/how-can-i-query-for-null-values-in-entity-framework – sTodorov 2011-06-03 06:51:36
@sTodorov:是的,我的解決方法是這樣的,但略有早些時候 - 所以你最終以一種簡單的謂詞結束。 – 2011-06-03 06:52:30