【问题标题】:Nullable optional parameter可空的可选参数
【发布时间】:2013-05-01 06:36:46
【问题描述】:

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

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

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&lt;Person&gt;,其中包含方法:

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()== 在这种情况下有什么区别。

【问题讨论】:

    标签: c# .net entity-framework-4 linq-to-entities


    【解决方案1】:

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

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

    当您传入parentPersonIDnull 时,这会将谓词更改为显式的空值检查,而不是使其与您传入的值匹配。很可能有一种更优雅的方式表达它,但至少值得一开始尝试。

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

    【讨论】:

    • 你的假设是正确的,是的。此外,显式检查有效(与 Equals() 的结果相同)。我很好奇如何处理具有值 null 的变量的相等性。后来也找到了这个:stackoverflow.com/questions/682429/…
    • @sTodorov:是的,我的解决方法是这样的,但稍早一些——所以无论哪种方式,你最终都会得到一个简单的谓词。
    猜你喜欢
    • 2018-08-10
    • 2017-03-16
    • 2013-06-02
    • 2011-09-26
    • 2023-02-22
    • 2019-12-06
    • 2018-08-22
    • 2018-07-26
    • 2018-12-17
    相关资源
    最近更新 更多