问题
I was trying to do the following
public IList<Category> GetMainCategories()
{
return _context.Category
.Where(x => x.ParentCategory == null)
.OrderBy(x => x.SortOrder)
.ToList();
}
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))
And
.Where(x => Equals(x.ParentCategory.Id, null))
.Where(x => Equals(x.ParentCategory, 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?
Update
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;
}
回答1:
If the query ...
_context.Category
.Where(x => x.ParentCategory == null)
.OrderBy(x => x.SortOrder)
.ToList()
... returns an empty collection it means that all categories in the database have a ParentCategory
or that the categories table is empty. That's all.
The fact that in the result collection of this query ...
_context.Category
.OrderBy(x => x.SortOrder)
.ToList()
... every category has no ParentCategory
doesn't prove that every category has no ParentCategory
in the database.
Do you know the basics of loading or not-loading related entities with EF? I suggest to read this introduction for EF >= 4.1/DbContext
: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx
回答2:
In your results it is not guaranteed that the references are actually null
in the database even if you see null
in your returned results.
Use this query to force EF to load the reference data:
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();
}
Note that the Include()
method does not impact how the Where
works, it just makes sure that when you view the ParentCategory
property in debugger window (or access from code) you will have the data there.
回答3:
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;
}
}
This should solve your problems as Entity Framerwork will use 'C# like' null comparison.
来源:https://stackoverflow.com/questions/11458514/where-clause-with-null-object-using-entity-framework-v5-0rc