簡體   English   中英

可空的可選參數

[英]Nullable optional parameter

我在 asp.net mvc 應用程序中使用帶有 edmx 文件和 POCO 的實體框架 4。

首先,我有一個人 class 映射到數據庫中的一個表。

public class Person
{
    public Int32 ID{get;set;}
    public string Name{get;set;}
    public Int32? ParentID{get;set;}
}

然后在我的服務層中,我有以下 function 來檢索所有人。 如果提供了 parentID,則檢索到的人將是具有該 parentID 的人:

public List<Person> Get(int? parentPersonID = null)
{
    var persons = Repository().GetAll(c => c.ParentID == parentPersonID);
}

最后,Repository() function 返回一個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);
}

一切都按預期工作。

任何想法為什么會這樣?

編輯:如果我將服務層 function 代碼替換為:

var persons = Repository().GetAll(c => c.ParentID.Equals(parentPersonID));

代替:

var persons = Repository().GetAll(c => c.ParentID == parentPersonID);

它按預期工作 - 第一行從數據庫中檢索記錄,而第二行沒有。 我仍然很好奇Equals()==在這種情況下有什么區別。

懷疑這與如何處理平等有關。 嘗試這個:

public List<Person> Get(int? parentPersonID = null) {
    var persons = Repository().GetAll(parentPersonID == null ? 
          c => !c.ParentID.HasValue :                
          c => c.ParentID == parentPersonID);
    ... 
}

當您傳入parentPersonIDnull時,這會將謂詞更改為顯式無效檢查,而不是使其與您傳入的值匹配。可能有一種更優雅的表達方式,但值得至少要嘗試開始。

(我假設如果您指定parentPersonIDnull ,您希望獲得所有具有null parentPersonID的人,而不僅僅是所有人......這將是一個不同的變化。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM