ToDictionary从第二个表中查询返回Null

时间:2016-06-29 15:35:04

标签: c# linq-to-sql repository-pattern

我有两个模型如下:

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输入的所有核对表的计数,但是当我从.Where的父表中添加另一个过滤器时,它返回null。当我从父表中取出.Where子句时,它可以正常工作。

修改尝试包括表格

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;
        }
    }

引发错误

  

抛出异常:&#39; System.ArgumentException&#39;在mscorlib.dll中.System.ArgumentException:类型为System.Func 2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier的表达式2 [CRAMSV3_2.Models.CHECKLIST,Microsoft.Data.Entity.Storage.ValueBuffer],System.Int32]&#39;不能用于System.Func类型的参数2[CRAMSV3_2.Models.CHECKLIST,System.Int32]' of method 'System.Collections.Generic.IEnumerable 1 [System.Linq.IGrouping 2[System.Int32,CRAMSV3_2.Models.CHECKLIST]] _GroupBy[CHECKLIST,Int32,CHECKLIST](System.Collections.Generic.IEnumerable 1 [CRAMSV3_2.Models.CHECKLIST],System.Func 2[CRAMSV3_2.Models.CHECKLIST,System.Int32], System.Func 2 [CRAMSV3_2.Models。一览表,CRAMSV3_2.Models.CHECKLIST])&#39;

问题使用多个表或仅一个表返回结果的最佳方法是什么,但要确保另一个表中的日期是可查询的。

1 个答案:

答案 0 :(得分:2)

您需要包含投诉对象。

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

相关问题