- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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);
...
}
当您传入 null
的 parentPersonID
时,这会将谓词更改为显式无效检查,而不是使其仅匹配您传入的值. 可能有更优雅的表达方式,但至少值得一试。
(我假设如果您指定一个 null
的 parentPersonID
,您希望让所有 的人都是一个 null parentPersonID
,而不仅仅是所有人...那将是一个不同的变化。)
关于c# - 可为空的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6223657/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!