简体   繁体   English

自引用多对多Linq查询

[英]Self Referencing Many-To-Many Linq Query

I have a datatable like this: 我有一个这样的数据表:

MtoM
{
   ParentID, 
   ChildID
}

Item
{
    ID,
    Data,
    Label
}

How do I write a linq query that returns every ChildID under a given ParentID and the associated Data and Label for each of these decendent IDs. 如何编写linq查询,该查询返回给定ParentID下的每个ChildID以及与每个后继ID关联的数据和标签。 If I were using SQL I'd use a union all and inner join , but I don't know linq well enough to do this. 如果我使用的是SQL,则将使用union allinner join ,但是我对linq的了解并不足够。

Performance is absolutely not an issue as there will be at most 3 levels of nesting and only 1 or 2 items in each level. 性能绝对不是问题,因为最多会有3个嵌套层,每个嵌套层只有1或2个项目。 The DDL I'm trying to populate is rarely used and is not mission critical. 我尝试填充的DDL很少使用,也不是关键任务。

assuming that child id is refering ID field in items table u can write following query to fetch required records 假设子ID引用项目表中的ID字段,您可以编写以下查询以获取所需的记录

from mt in MToM 
where mt.ParentID == GivenParentID
join it in Item on mt.ChildId equals it.ID
select new { parentID = mt.ParentID, childID = it.ID, childData = it.Data, childLabel = it.Label}

data is being returned in anonymous type. 数据以匿名类型返回。 u can create new Type and populate it with resultant records 您可以创建新的Type并用结果记录填充它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM