自我加入Linq查询 [英] Self joining Linq query

查看:68
本文介绍了自我加入Linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我在构建Linq查询时有点困惑。 


我有2个表" groups"和"产品"



组表存在


Id

ParentId

名称


产品表存在


Id

GroupId
名称


最困难的部分是构建Linq查询以获取所有组,子组和子组的子项。


<我还必须检查文章表是否包含组ID。


这是因为我正在构建我的菜单结构,只显示包含产品的组和子组。


任何想法是否有可能或一些建议开始?这是一个困难的。




解决方案

嗨Kris1981,


>>任何想法是否有可能或一些建议开始?这是一个困难的。



它似乎我们可以使用递归方法来实现它,如下所示:


#Groups model

 public partial class Group 
{
public Menu()
{
this.Group1 = new HashSet< Group>();
this.Products = new HashSet< Product>();
}

public int Id {get;组; }
public string Name {get;组; }
public Nullable< int> ParentID {get;组; }
public virtual ICollection< Group>第1组{get;组; }
public virtual Group Group2 {get;组; }
public virtual ICollection< Product>产品{get;组; }
}

#Related Code

 void GetChildren(组当前){
if(current == null){
return;
} else {
dbContext.Entry(current).Collection(m => m.Group1).Load(); //从数据库中检索
foreach(m.Group1中的var group){
GetChildren(group);
}
}
}

祝你好运,


章龙


Hello,

I'm a bit stuck on building a Linq query. 

I have 2 tables "groups" and "products"

Groups table exists of

Id
ParentId
Name

Products table exists of

Id
GroupId
Name

Well the most difficult part is to build a Linq query to get all groups, child groups and child of child groups.

I also have to check if the article table contains the group id.

It's because i'm building my menu structure to show only groups and children groups which contains products.

Any idea if this is possible or some advice to get started? It's a difficult one.

解决方案

Hi Kris1981,

>>Any idea if this is possible or some advice to get started? It's a difficult one.

It seems that we could use a recursive method to achieve it, like this:

#Groups model

public partial class Group
{
    public Menu()
    {
        this.Group1 = new HashSet<Group>();
        this.Products = new HashSet<Product>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public Nullable<int> ParentID { get; set; }
    public virtual ICollection<Group> Group1 { get; set; }
    public virtual Group Group2 { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

#Related Code

void GetChildren(Group current) {
    if (current == null) {
        return;
    } else {
        dbContext.Entry(current).Collection(m => m.Group1).Load(); // retrieve from database
        foreach (var group in m.Group1) {
            GetChildren(group);
        }
    }
}

Best regards,

Zhanglong


这篇关于自我加入Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆