繁体   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