int32.Equals int之间的区别? == int?对于linq

时间:2012-03-04 04:35:34

标签: asp.net-mvc linq equality

我知道标题不是很清楚,但这是问题所在。我正在尝试用asp.net mvc开发简单的网页,我有类别控制器,并尝试在下面的代码块解释情况。

    //
    // GET: /Category/
    public ViewResult Index(int? id)
    {

        if (id == null)
        {
            //Gives the following error if nut null, 1,2 etc
            //Unable to cast the type 'System.Nullable`1' to type 'System.Object'. 
            //LINQ to Entities only supports casting Entity Data Model primitive types.
            var categories = db.Categories.Where( c => Int32.Equals(c.ParentCategoryId, id));
            return View(categories);
        }
        else
        {
            //Does not show any category, must show item if ParentCategoryId is null
            var categories = db.Categories.Where(c => c.ParentCategoryId == id);
            return View(categories);
        }
    }

我的数据是

ID    Name            ParentId
----------------------------------
1   Computer    NULL
2   TV          NULL
3   Laptop          1
4   Desktop         1

3 个答案:

答案 0 :(得分:1)

当使用Linq时,答案取决于Linq提供程序的实现以及他们如何选择处理这种情况。

当你写c => c.ParentCategoryId == id时,这是一个表达式树。 Linq提供程序将其分解为(1)属性访问(ParentCategoryId),(2)变量访问(id),以及(3)它将两个操作数连接在一起进行相等比较( ==)。此代码实际上不作为函数运行,它只是作为表达式处理

同样,c => Int32.Equals(c.ParentCategoryId, id)被分解为一个方法调用(Int32.Equals),它带有两个参数。 Linq提供商选择实现与Int32.Equals的呼叫与==相同,然后这应该是相同的。但是,他们更可能没有

第二个Linq声明可能已转换为

select * from Categories where ParentCategoryId = NULL

在ANSI SQL中永远不会这样,因此每次都会获得0条记录。你会更好地说.Where(x => x.ParentCategoryId != null).Where(x => x.ParentCategoryId.HasValue)。同样,这取决于Linq提供商的创建者选择了什么,但其中一个必然会以您期望的方式工作。

答案 1 :(得分:1)

    public ViewResult Index(int? id = 0)
    {
        var categories = db.Categories
            .Where(c => (c.ParentId.HasValue ? c.ParentId : 0) == id)
                 .ToList();
        return View(categories);
    }

答案 2 :(得分:0)

试试这段代码:

    if (id == null)
    {
      var categories = db.Categories.Where( c => !c.ParentCategoryId.HasValue); 
      ..             
    }