使用实体框架v5.0RC的空对象 [英] Where Clause With Null Object Using Entity Framework v5.0RC

查看:114
本文介绍了使用实体框架v5.0RC的空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下

    public IList<Category> GetMainCategories()
    {
         return _context.Category
                 .Where(x => x.ParentCategory == null)
                 .OrderBy(x => x.SortOrder)
                 .ToList();
    }

然而,无论我尝试什么都不会返回任何结果,即使我可以看到在所有ParentCategory为null的集合中?我读过EF有这样的null的问题,并且还试过

However, no matter what I try this returns no results even though I can see in the collection that ALL ParentCategory's are null? I have read EF has problems with nulls like this and have also tried

.Where(x => x.ParentCategory.Equals(null))

.Where(x => Equals(x.ParentCategory.Id, null))
.Where(x => Equals(x.ParentCategory, null))

但结果仍然相同?我迷路了?我如何检查对象是否为空?当我在VS2010中检查它是否清楚地表示它的null?

But still same result? I'm lost? How the heck do I check if an object it null? When I inspect it in VS2010 is clearly states its null?

更新

我可以让它工作这样做,但它的疯狂低效!在查询中必须能够做到这一点,或者我非常震惊EF!任何帮助非常感谢?

I can get it working doing this, BUT its insanely inefficient!!! MUST be able to do this in the query or I'm rather shocked by EF! Any help greatly appreciated?

    public IList<Category> GetMainCategories()
    {
        var cats = _context.Category
                 .OrderBy(x => x.SortOrder)
                 .ToList()
                 .Where(cat => cat.ParentCategory == null)
                 .ToList();
        return cats;
    }


推荐答案

可能已经过时了,但是猜想这是你正在寻找的答案:

It might be outdated but I guess this is the answer you were looking for:

public abstract class YourContext : DbContext
{
  public YourContext()
  {
    (this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
  }
}

这应该解决您的问题,因为实体Framerwork将使用' C#喜欢'null比较。

This should solve your problems as Entity Framerwork will use 'C# like' null comparison.

这篇关于使用实体框架v5.0RC的空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆