可为null的可选参数

本文关键字:参数 null 可为 | 更新日期: 2023-09-27 17:58:23

我在asp.net mvc应用程序中使用带有edmx文件和POCO的实体框架4。

首先,我有一个person类,它被映射到数据库中的一个表。

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);
}

最后,Repository()函数返回一个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);

它按预期工作——第一行从DB中检索记录,而第二行则不然。我仍然很好奇在这种情况下Equals()==有什么不同。

可为null的可选参数

I怀疑这与如何处理平等有关。试试这个:

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

当您传入nullparentPersonID时,这将把谓词更改为显式的无效性检查,而不是让它与您传入的值匹配。很可能有一种更优雅的表达方式,但至少值得一试。

(我假设,如果你指定nullparentPersonID,你想让所有带有空parentPersonID的人,而不仅仅是所有的人……这将是一个不同的变化。)