gpt4 book ai didi

c# - 可为空的可选参数

转载 作者:行者123 更新时间:2023-11-30 17:17:48 26 4
gpt4 key购买 nike

我在 asp.net mvc 应用程序中使用带有 edmx 文件和 POCO 的 Entity Framework 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);

它按预期工作 - 第一行从数据库中检索记录,而第二行没有。我仍然很好奇 Equals() 有什么区别和 ==在这种情况下。

最佳答案

怀疑这与处理平等的方式有关。试试这个:

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

当您传入 nullparentPersonID 时,这会将谓词更改为显式无效检查,而不是使其仅匹配您传入的值. 可能有更优雅的表达方式,但至少值得一试。

(我假设如果您指定一个 nullparentPersonID,您希望让所有 的人都是一个 null parentPersonID,而不仅仅是所有人...那将是一个不同的变化。)

关于c# - 可为空的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6223657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com