0

我有一个类别表,它有一个可以为空的 parentId 字段的外键。在 Entity-Framework 中创建关系时,生成的实体没有任何关系字段。我的意思是,在我的示例中,当我在 Category 表中创建 parentId-Id 关系时,生成的 Category Entity 将具有一个 int 类型的 Id 属性和一个 Category 类型的 ParentCategory 属性,并且没有 ParentId 属性。这使我的查询更加困难。

所以,当我想选择一个类别的子类别时,我遇到了麻烦。我使用下面的方法;

public IEnumerable<ICategory> GetSubCategories(long? categoryId)
{
    var subCategories = this.Repository.Category.Where(c => c.ParentCategory.Id == categoryId)
                .ToList().Cast<ICategory>();

    return subCategories;
}

但这不起作用,当我想选择根类别时。这样做的方法是什么?

顺便说一句,我想知道是否有一种方法可以生成像 Linq to Sql 这样的实体,具有 int 类型的 Id 属性、int 类型的 ParentId 和 Category 类型的 ParentCategory 属性。

4

1 回答 1

1

要选择根类别:

var rootCategories = this.Repository.Category.Where(c => c.ParentCategory == null).ToList().Cast<ICategory>();

概括代码以同时使用子和根类别:

var rootCategories = this.Repository.Category.Where(c => categoryId == null ? c.ParentCategory == null : c => c.ParentCategory.Id == categoryId).ToList().Cast<ICategory>();
于 2009-02-25T13:25:23.170 回答