0

我尝试做以下WHERE子句与空对象使用实体框架v5.0RC

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

然而,无论怎样我尝试这不返回任何结果,即使我可以在收藏看到,所有ParentCategory的是空的?我已阅读EF有这样的空值问题,也试图

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

而且

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

但还是同样的结果?我迷路了?我该如何检查一个对象是否为空?当我在VS2010中检查它是否明确指出它为空?

更新

我能得到它的工作这样做,但它的疯狂效率低下!必须能够在查询中做到这一点,或者我非常震惊EF!任何帮助不胜感激?

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

请发布EF生成的SQL。是的,EF的查询功能在很大程度上落后于其前身LINQ to SQL。 – usr 2012-07-12 19:12:30

+0

你的模型是什么样的?类别模型? – 2012-07-12 19:16:19

+0

当查询返回没有结果时,我想知道什么“集合”你看到“所有ParentCategory的都是空的”。 – Slauma 2012-07-12 22:10:55

回答

0

如果查询...

_context.Category 
     .Where(x => x.ParentCategory == null) 
     .OrderBy(x => x.SortOrder) 
     .ToList() 

...返回一个空集则意味着数据库中的所有类别有ParentCategory或类别表是空的。就这样。

这个查询的结果集...

_context.Category 
     .OrderBy(x => x.SortOrder) 
     .ToList() 

在...每个类别有没有ParentCategory并不能证明每个类别在数据库中没有ParentCategory的事实。

您是否知道使用EF加载或不加载相关实体的基础知识?我建议阅读本介绍了EF> = 4.1/DbContexthttp://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

+0

我用dbContext使用v5.0RC,.Include()方法只想要一个字符串?不接受lambda?我没有.Collection()方法可用? – leen3o 2012-07-13 05:15:47

+0

@ leen3o:你可以尝试使用System.Data.Entity;将命名空间添加到你的代码文件中。如果这并不能解决这个问题,我还没有使用v5。对于EF 4.x,至少名称空间可以解决问题。 – Slauma 2012-07-13 10:12:47

+0

fwiw,我发现resharper 7(预览版,也许#28?)intellisense阻止了允许包含lambda表达式的intellisense,即使我们使用了system.data.entity语句。 JetBrains意识到这一点,它现在甚至可能会被修复。所以如果你有System.Data.Entity但仍然没有得到lambda intellisense的支持,那可能是为什么。 – 2012-07-21 15:24:06

0

在您的结果时,不能保证引用实际上null在数据库中,即使你看到Google返回的结果null

使用此查询强制EF加载参考数据:

public IList<Category> GetMainCategories() 
{ 
    return _context.Category 
      .Include(x => x.ParentCategory) // for the new EF versions 
      .Include("ParentCategory")  // for older EF versions 
      // .Where(x => x.ParentCategory == null) 
      .OrderBy(x => x.SortOrder) 
      .ToList(); 
} 

注意,Include()方法不影响如何Where的作品,它只是确保当您查看在调试器窗口中的ParentCategory财产(或从代码访问)你将有数据在那里。

0

它可能已过时,但我想这是你要找的答案:

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

这应该解决您的问题,实体Framerwork将使用“C#喜欢”无效的比较。