Entityframework在调用parent时选择所有childs相关数据

时间:2015-05-06 12:07:07

标签: c# asp.net-mvc entity-framework

我有类别表,其中包含:

public partial class C_Categories
{
    public int CatId { get; set; }
    public Nullable<int> ParentId { get; set; }
    public string ImageUrl { get; set; }

    public virtual ICollection<C_Node> C_Node { get; set; }
}

我有节点表,其中包含:

public partial class C_Node
{
    public int NodeId{ get; set; }
    public Nullable<int> CatId { get; set; }
    public System.DateTime PostDate { get; set; }

    public virtual C_Categories C_Categories { get; set; }
}

我的控制员:

public ActionResult Index(int? catId)
{
    IQueryable<C_Node> moduleItems = db.C_Node;
    if (catId != null)
    {
        //here i want to check if category is parent , get all node related to his child categories
        moduleItems = moduleItems.Where(x => x.CatId == catId);
    }

    return View(moduleItems.ToList());
}

在我的控制器中,我想检查类别是否为父类,获取与其子类别相关的所有节点表,
我尝试使用任何,但它失败了。
 解释我的问题:我有类别:电子和电子产品有儿童电脑,手机。我在计算机和手机下的节点表上有产品,如果catId是电子产品我想要所有产品在其子产品计算机,手机下

2 个答案:

答案 0 :(得分:1)

首先需要找到父母下的所有类别;如果只有2个级别,这很简单:

...

if (catId != null)
{
    // Find the child categories for which this is the parent    
    var childCatIds = db.C_Categories
     .Where(cat => cat.ParentId == catId)
     .Select(cat => cat.CatId)
     .ToList();
    if (childCatIds.Count == 0)
    // Not a parent category: Just find the items for the category as before
        moduleItems = moduleItems.Where(x => x.CatId == catId);
    else
        // Parent category: Find the items for the child categories
        moduleItems = moduleItems.Where(x => childCatIds.Contains(x.CatId));
}

如果有超过2个级别,则需要递归找到子ID。

private List<int> GetChildCatIds(List<int> parentCatIds)
{
        var childCatIds = db.C_Categories
          .Where(cat => cat.ParentId.HasValue && parentCatIds.Contains(cat.ParentId.Value))
          .Select(cat => cat.CatId)
          .ToList();
        if (childCatIds.Count == 0)
            // Reached the end of the tree: no more children
            return parentCatIds;
        else
            // Recursive call to find the next child level:
            return GetChildCatIds(childCatIds);
}


...

if (catId != null)
{    
    var childCatIds = GetChildCatIds(new List<int>{catId.Value});
    moduleItems = moduleItems.Where(x => childCatIds.Contains(x.CatId));
}

答案 1 :(得分:0)

这个怎么样:

moduleItems = dbcontext.C_Nodes.Where(n => n.CatId == catId);