任务的项目的编码器的团队。
如何使用方法语法和Code First方法(实体框架中的任务的数量有效地对团队进行排序(可能不会加载子项的子集的整个集合内容) ,我只需要排序)?
public class MyAppContext : DbContext
{
public DbSet<CTeam> Teams { get; set; }
// ...etc
}
[Table("Team")]
public class CTeam
{
public int ID { get; set; }
[MaxLength(128)]
public string Title { get; set; }
[Display(Name = "Coders")]
public virtual ICollection<CCoder> Coders { get; set; }
}
[Table("Coder")]
public class CCoder
{
public int ID { get; set; }
[MaxLength(128)]
public string Name { get; set; }
public virtual ICollection<CProject> Projects { get; set; }
public int TeamID { get; set; }
public virtual CTeam Team { get; set; }
}
// CProject and CTask similarly
或者,如果你能给出一个提示原始SQL应该是什么样的提示,这也会有所帮助。谢谢!
更新
在关系Builder -> NewBuildingObject -> NewBuildingHouse -> NewBuildingLayout
为了观众的方便, Teodor Ivanov 的回答:
context.Teams
.OrderBy(x => x.Coders
.SelectMany(y => y.Projects)
.SelectMany(y => y.Tasks)
.Count());
使EF生成此代码:
SELECT
[Project1].[ID] AS [ID],
[Project1].[Title] AS [Title]
FROM ( SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Title] AS [Title],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[NewBuildingObject] AS [Extent2]
INNER JOIN [dbo].[NewBuildingHouse] AS [Extent3] ON [Extent2].[ID] = [Extent3].[ObjectID]
INNER JOIN [dbo].[NewBuildingLayout] AS [Extent4] ON [Extent3].[ID] = [Extent4].[HouseID]
WHERE [Extent1].[ID] = [Extent2].[BuilderID]) AS [C1]
FROM [dbo].[Builder] AS [Extent1]
) AS [Project1]
ORDER BY [Project1].[C1] ASC
和 Yacoub Massad 的回答:
var teams = context.Teams
.OrderBy(team =>
team.Coders.SelectMany(coder =>
coder.Projects.SelectMany(project => project.Tasks)).Count());
制作了这段代码:
SELECT
[Project1].[ID] AS [ID],
[Project1].[Title] AS [Title]
FROM ( SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Title] AS [Title],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[NewBuildingObject] AS [Extent2]
INNER JOIN (SELECT [Extent3].[ObjectID] AS [ObjectID]
FROM [dbo].[NewBuildingHouse] AS [Extent3]
INNER JOIN [dbo].[NewBuildingLayout] AS [Extent4] ON [Extent3].[ID] = [Extent4].[HouseID] ) AS [Join1] ON [Extent2].[ID] = [Join1].[ObjectID]
WHERE [Extent1].[ID] = [Extent2].[BuilderID]) AS [C1]
FROM [dbo].[Builder] AS [Extent1]
) AS [Project1]
ORDER BY [Project1].[C1] ASC
答案 0 :(得分:3)
您可以尝试类似
的内容context.Teams
.OrderBy(x => x.Coders
.SelectMany(y => y.Projects)
.SelectMany(y => y.Tasks)
.Count());
答案 1 :(得分:2)
您可以像这样使用SelectMany
:
var teams = context.Teams
.OrderBy(team =>
team.Coders.SelectMany(coder =>
coder.Projects.SelectMany(project => project.Tasks)).Count());