5

我正在尝试列出一些类别(父子关系),并且我有以下命令仅列出父类别

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

但是EF生成的sql查询没有返回任何东西

EF生成的sql查询

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

类别模型

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();
  }
}

映射

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);
  }
}
4

1 回答 1

0

我将其发布为答案,因为其中之一肯定会起作用:

您的ParentId财产需要public virtual- 尝试先改变它。

那么,试试context.Categories.Where(c => !c.ParentId.HasValue)

那么,试试context.Categories.Where(c => c.Parent == null)

我有上述工作正常的应用程序。

那么,试试context.Categories.Where(c => object.Equals(c.Parent, null))

最后一个有点来自 MS 的某个人的黑客攻击,但显然应该可以工作。

于 2013-03-31T13:21:32.830 回答