EF Code First null comparison generates strange query

I am trying to list some categories (parent child relationships) and I have the following command to list only parent categories

context.Categories.Where(c => c.ParentId == null)

But sql query generated by EF returns nothing

sql query created by EF

SELECT 
CAST(NULL AS int) AS [C1], 
CAST(NULL AS varchar(1)) AS [C2], 
CAST(NULL AS bit) AS [C3], 
CAST(NULL AS int) AS [C4]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
WHERE 1 = 0

model category

public class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
  public bool IsActive { get; set; }
  public virtual IList<Category> SubCategories { get; set; }
  internal int? ParentId { get; set; }
  public virtual Category Parent { get; set; }

  public override bool Equals(object obj)
  {
    var categoryToCompare = obj as Category;
    if (categoryToCompare == null) return false;

    return categoryToCompare.Id == Id;
  }

  public override int GetHashCode()
  {
    return Id.GetHashCode();
  }
}

Mapping

public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
  public CategoryConfiguration()
  {
    ToTable("tbl_category");
    HasKey(c => c.Id);
    Property(c => c.Id).HasColumnName("cd_category");
    Property(c => c.Name).HasColumnName("ds_category");
    Property(c => c.IsActive).HasColumnName("fl_active");
    Property(c => c.ParentId).HasColumnName("cd_base_category").IsOptional();
    HasMany(c => c.SubCategories).WithRequired(c => c.Parent).HasForeignKey(c => c.ParentId);
  }
}
+5
source share
1 answer

I am posting this as an answer, because surely one of them will work:

The property ParentIdshould be public virtual- first try changing this.

Then try context.Categories.Where(c => !c.ParentId.HasValue)

Then try context.Categories.Where(c => c.Parent == null)

I have applications in which this works fine.

Then try context.Categories.Where(c => object.Equals(c.Parent, null))

- MS, , , .

0

All Articles