2017-09-16 34 views
0

在开发中ASP.NET CORE我遇到了以下问题的应用程序:加载集合内从一个集合中的项LINQ实体框架的核心

我有一个DBSet<UserHistory>。我需要做的是访问UserHistory中的Sessions元素。然后我需要从会话元素访问作业里面的最后一个元素。

理想情况下,我想只加载一个元素而不加载所有集合。

我试过以下,它不工作:

...

var item = userHistory.Where(n=>Name == name).Include(s=>s.Sessions).Last(). 
    ThenInclude(j=>j.Jobs).Last(); 

任何帮助将不胜感激。谢谢!

public class UserHistory 
{ 

    public int Id { get; set; } 

    public string UserId { get; set; } 

    public List<SessionHistory> Sessions { get; set; } 


    public UserHistory() 
    { 

    } 
} 


public class SessionHistory 
{ 

    public int Id { get; set; } 
    public DateTime ClockIn { get; set; } 
    public DateTime ClockOut { get; set; } 

    public List<JobHistory> Jobs { get; set; } 


    // The flaged must be set when the user clocks out 
    public bool IsClockedOut { get; set; } 

    public SessionHistory() 
    { 
     Jobs = new List<JobHistory>(); 
    } 
} 

public class JobHistory 
{ 
    public int Id { get; set; } 
    public string CompanyName { get; set; } 
    public int JobNumber { get; set; } 
    public string JobDescription { get; set; } 

    public DateTime JobStart { get; set; } 
    public DateTime JobFinish { get; set; } 


    // Will be set to true when signed out of the job 
    // Use it to determain if the the user is signed out! 
    public bool IsJobComplete{ get; set; } 
} 
+1

'Include'仅包括整个集合(当应用于集合导航属性,当然)。不涉及排序或过滤。你必须编写一个LINQ查询,在“Select”语句中获得所需的结果。 –

回答

0

首先:

这部分(n=>Name == name)应该是(n=>n.Name == name),不应该吗?

然后尝试类似:

var item = userHistory.Where(n=>n.Name == name).First().Sessions.Last().Jobs.Last();