c# - 如何使用 LINQ 查询此分层数据?

标签 c# linq linq-to-sql

我有 3 种对象:Agency、BusinessUnit 和 Client(每个对象都有各自的表)

在层次结构方面,代理商拥有业务部门,而业务部门拥有客户。

我有 3 个 C# POCO 对象来表示它们(我通常在其中选择新的 {},而不是使用 LINQ 生成的类):

public class Agency
{
    public IEnumerable<BusinessUnit> BusinessUnits { get; set; }
}

public class BusinessUnit
{
    public IEnumerable<Client> Clients { get; set; }
}

public class Client
{
    public int NumberOfAccounts { get; set; }
    public Decimal AmountOfPlacement { get; set; }
    public Decimal AvgBalance { get; set; }
    public Double NeuPlacementScore { get; set; }
}

您可以看到 Agencies 包含 BusinessUnits 列表,而 BusinessUnits 包含 Clients 列表。

我在数据库中还有一个名为 BAC_Map 的映射表,它表示谁拥有谁,它看起来像这样:

alt text

如何构建查询,以便查询并返回代理商列表?这意味着,我希望每个 Agency 都设置其 BusinessUnit 对象列表,并且我希望 BusinessObjects 列表设置其 Clients 列表。

我可以进行基本的 LINQ 查询,但是关于 Map 表和倍数,这让我有些头疼?查询。

我如何构建像 GetAllAgencies() 这样的方法,它不仅可以查询所有代理机构,还可以填充代理机构拥有的 BusinessUnits 以及这些 BusinessUnits 拥有的客户?


编辑:感谢任何提示或信息。我需要加入吗?这是否需要多次查询才能返回代理列表,并填充其子成员?

最佳答案

如果您将所有四个表(Agency、BusinessUnit、Client、Map)放在 linq to sql 设计器上,并绘制从 Map 到其他三个的关系,Map 上会有一些有用的属性。

  //construct a query to fetch the row/column shaped results.
var query = 
  from m in db.map
  //where m.... ?
  let a = m.Agency
  let b = m.BusinessUnit
  let c = m.Client
  // where something about a or b or c ?
  select new {
    AgencyID = a.AgencyID,
    AgencyName = a.Name,
    BusinessUnitID = b.BusinessUnitID,
    ClientID = c.ClientID,
    NumberOfAccounts = c.NumberOfAccounts,
    Score = c.Score
  };
  //hit the database
var rawRecords = query.ToList();

  //shape the results further into a hierarchy.    
List<Agency> results = rawRecords
  .GroupBy(x => x.AgencyID)
  .Select(g => new Agency()
  {
    Name = g.First().AgencyName,
    BusinessUnits = g
    .GroupBy(y => y.BusinessUnitID)
    .Select(g2 => new BusinessUnit()
    {
      Clients = g2
      .Select(z => new Client()
      {
        NumberOfAccounts = z.NumberOfAccounts,
        Score = z.Score
      })
    })
  })
  .ToList();

如果提供了适当的过滤器(请参阅注释掉的 where 子句),则只会将表中需要的部分拉入内存。这是在这里工作的标准 SQL 连接。

关于c# - 如何使用 LINQ 查询此分层数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1041312/

相关文章:

c# - 在 Entity Framework 6 中使用规范化数据?

c# - 'where' 条件无效。实体成员正在调用无效的属性或方法

asp.net - 查询LINQ to SQL关系

c# - 使用 Group by 的 Linq to SQL

c# - 更新 IEnumerable 中的项目属性但该属性未保持设置?

c# - 生成带步长值的序列

.net - ListViewItemCollection 的字符串数组

linq - 在LINQ中学习表达式树

asp.net - LINQ to SQL、ExecuteQuery 等

c# - LINQ:SubmitChanges() 没有更新我的记录