ToDictionary 从第二个查询 table returns Null

ToDictionary Querying from second table returns Null

我有两个型号如下:

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 virtual COMPLAINT Complaints { get; set; }
}

我有一个存储库,它查询 EMPID 输入的所有清单并 returns 计数,但是当我从 .Where 的父 table 添加另一个过滤器时,它 return 为空。当我从父 table 中取出 .Where 子句时,它工作得很好。

编辑 尝试包含 table

public Dictionary<int, int> GetAllChecklistCount()
    {
        try
        {
            return _context.Checklists
                .Where(t => t.Complaints.Received_DT.Value.Year == 2016) 
                .Include(t => t.Complaints)
                .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;
        }
    }

抛出错误

Exception thrown: 'System.ArgumentException' in mscorlib.dll System.ArgumentException: Expression of type System.Func2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier2[CRAMSV3_2.Models.CHECKLIST,Microsoft.Data.Entity.Storage.ValueBuffer],System.Int32]' cannot be used for parameter of type System.Func2[CRAMSV3_2.Models.CHECKLIST,System.Int32]' of method 'System.Collections.Generic.IEnumerable1[System.Linq.IGrouping2[System.Int32,CRAMSV3_2.Models.CHECKLIST]] _GroupBy[CHECKLIST,Int32,CHECKLIST](System.Collections.Generic.IEnumerable1[CRAMSV3_2.Models.CHECKLIST], System.Func2[CRAMSV3_2.Models.CHECKLIST,System.Int32], System.Func2[CRAMSV3_2.Models.CHECKLIST,CRAMSV3_2.Models.CHECKLIST])'

问题 return 有多个 table 或只有一个 table 结果的最佳方法是什么,但要确保日期来自另一个 table 是可查询的。

您需要包含投诉对象。

return _context.Checklists
            .Where(t => t.Complaints.Received_DT.Value.Year == 2016)
            .Include(t => t.Complaints)
            .GroupBy(a => a.EmpID)
            .ToDictionary(g => g.Key, g => g.Count());

详情见here