【问题标题】:How to get the parent and only the first child of a related table如何获取相关表的父级和唯一的第一个子级
【发布时间】:2012-04-10 15:57:33
【问题描述】:

我有这 3 张桌子:

Process、Action 和 Process_Actions(多对多,它注册了一个 Process 可以执行的所有 Actions。基本上,这个表有 Process_Id、Action_Id 和一个唯一的 ID(订购)。

我想要的是一个 LINQ 查询来获取所有 Process 的列表并只获取最后一个 Action(按日期排序)

这是我的工作 SQL 查询:

SELECT P.Id, P.Name, PA.Action_Id FROM Process P
    JOIN Process_Actions PA ON P.Id = PA.Process_Id 
    WHERE PA.Id IN (SELECT MAX (PA.Id) FROM Process_Actions INNER JOIN Process_Actions PA ON P.Id = PA.Process_Id)

【问题讨论】:

  • 嗯...我在您的 T-SQL 示例中没有看到操作引用。
  • 我只需要在 Process_Actions 中引用的 Action_Id

标签: .net sql linq c#-4.0 entity-framework-4


【解决方案1】:

试试这个:

context.Processes.Select(p => new { Process = p,
    LastAction = p.Actions.OrderbyDescending(a => a.Date).FirstOrDefault() } )

假设Action 有一个属性Date(正如你所说的按日期排序)。

【讨论】:

    【解决方案2】:

    我会尝试这样的事情

    var maxId = (from pa in context.Process_Actions 
    join pa on pa.Id = pa.Process_Id)
    select (int?)pa.Id).Max();
    
    var query = from p in context.Process
    join pa in context.Process_Actions on p.Id equals pa.Process_Id
    where maxId.Contains(pa.Id)
    select new
    {
        p.Id, 
        p.Name, 
        pa.Action_Id
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多