首页 > 解决方案 > 使用 LinkEntity 从 EntityCollection 获取数据组

问题描述

我有一个使用 QueryExpression 和 LinkEntity (InnerJoin) 检索的扁平数据结构。我用“元素”给孩子起了别名

所以我的数据看起来像这样:

parentIdPK     parentStatus     element.ChildIdPK     element.parentIdFK
1              100              10                    1
1              100              11                    1
1              100              12                    1
2              100              13                    2
2              100              14                    2
3              100              15                    3
3              100              16                    3
3              100              17                    3

所以基本上我有一个父/子结构,我想将这些数据推送到我自己的类中:

public class ExistingProposal
{
   public Guid parentIdPK { get; set; }
   public int parentStatus { get; set; }
   public List<ExistingElement> Elements { get; } = new List<ExistingElement>();
}

public class ExistingElement
{
   public Guid ChildIdPK { get; set; }
   public Guid parentIdFK { get; set; }
}

所以一般来说,这将导致一个 ExistingProposal 与 N ExistingGRProposalElement's

我能以最好的方式实现这一目标吗?我已经尝试过使用 linq,但我对此非常挣扎。

我实际上正在尝试使用 linq 对数据进行分组:

var groups = from a in result.Entities
    orderby a.Attributes["parentId"]
    group a by a.Attributes["parentId"] into g
    select new { g };

我实际上遇到的问题是我不知道从哪里开始创建所需的类结构。

也许有人可以指出我正确的方向?

任何提示都非常感谢。

标签: c#linq

解决方案


您的问题不是很清楚,但是,如果我理解得很好,以下表达式将为您解决问题:

var groups = from a in result.Entities
group a by a.Attributes["parentId"] into g
select new ExistingProposal {
    parentIdPK = a.Key,
    parentStatus = (int)a.FirstOrDefault().Attributes["parentStatus"],
    Elements = (from y in g
               select new ExistingElement {
                   ChildIdPK = y.Attributes["element.ChildIdPK"],
                   parentIdFK  = a.Key
               }).ToList()
};
  1. 您需要在您的Elements属性中添加一个 setterExistingProposal
  2. 分组前无需下单
  3. 您应该将中间变量(y、g、a 等)重命名为更有意义的变量

推荐阅读