我试图列出一些类别(父子关系),我有以下命令只列出父类别
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);
}
}
答案 0 :(得分: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))
最后一个是bit of a hack from someone at MS,但显然应该有效。