包括Linq到Sql的第二个表

时间:2016-06-27 21:16:10

标签: c# linq dictionary linq-to-sql

我有一个字典结果,它返回输入的每个核对表的计数。

这些课程如下:

public class COMPLAINT
{
    [Key]
    public int COMP_ID { get; set; }
    public Nullable<DateTime> Received_DT { get; set; }
    public virtual ICollection<CHECKLIST> CHECKLISTs { get; set; }
}

public class CHECKLIST
{
    [Key]
    public int CL_ID { get; set; }
    public int EmpID { get; set; }
    public int COMP_ID { get; set; }
}

当我只返回_context.Checklists时,我得到了我想要返回的总数,如下所示。

public Dictionary<int, int> GetAllComplaintsCount()
    {
        try
        {
            return _context.Checklists

                .GroupBy(a => a.EmpID)
                .ToDictionary(g => g.Key, g => g.Count());
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get am with checklist", ex);
            return null;
        }
    }

问题 但是当我添加投诉表时,我收到的错误是EmpID不在投诉表中,但是它在清单表中。如何通过EmpID包含投诉表和组,但是也可以在收到日期之间查询?

public Dictionary<int, int> GetAllComplaintsCount()
    {
        try
        {
            return _context.Complaints
                .Include(t=> t.Checklists)
                .GroupBy(a => a.EmpID)
                .ToDictionary(g => g.Key, g => g.Count());
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get am with checklist", ex);
            return null;
        }
    }

1 个答案:

答案 0 :(得分:1)

仍然在核对清单上遗漏了您的投诉属性,但假设这是另一种疏忽,我认为这就是您想要的:

public Dictionary<int, int> GetAllComplaintsCount(DateTime start, DateTime finish)
{
  try
  {
    return _context.Checklists
      .Where(a=>a.Complaint.Received_DT>=start && a.Complaint.Received_DT<finish)
      .GroupBy(a => a.EmpID)
      .ToDictionary(g => g.Key, g => g.Count());
  }
  catch (Exception ex)
  {
    _logger.LogError("Could not get am with checklist", ex);
    return null;
  }
}