【问题标题】:Not able to use IN query in LINQ with Entity Framework无法在带有实体框架的 LINQ 中使用 IN 查询
【发布时间】:2017-07-21 07:24:59
【问题描述】:

我正在使用 EF 框架从 SQL DB 中检索数据。

子请求表如下所示:

在此表中,“org_assigneddept”是另一个部门表的外键。

我有部门列表作为输入,我只想从 org_assigneddept 与列表匹配的 DB 中检索那些行。

请找到我的完整代码:-

   private List<EventRequestDetailsViewModel> GetSummaryAssignedDeptEventRequests(List<EmpRoleDeptViewModel> vmDept)
            {
                List<EventRequestDetailsViewModel> vmEventRequestDeptSummary = new List<EventRequestDetailsViewModel>();

                RequestBLL getRequestBLL = new RequestBLL();
                Guid subRequestStatusId = getRequestBLL.GetRequestStatusId("Open");

                using (var ctxGetEventRequestSumm = new STREAM_EMPLOYEEDBEntities())
                {
                    vmEventRequestDeptSummary = (from ers in ctxGetEventRequestSumm.SubRequests                                                                                    
                                                 where vmDept.Any(dep=>dep.DeptId == ers.org_assigneddept)  
                                                 select new EventRequestDetailsViewModel
                                                 {
                                                     SubRequestId = ers.org_subreqid
                                                 }).ToList();
                }
           }

它在 LINQ 查询级别给出以下错误:-

System.NotSupportedException: '无法创建常量值 键入“Application.Business.DLL.EmpRoleDeptViewModel”。只有原始 在此上下文中支持类型或枚举类型。'

请告诉我如何才能达到结果

【问题讨论】:

    标签: entity-framework linq linq-to-entities


    【解决方案1】:

    您不能将部门虚拟机传递给 SQL,它不知道它们是什么。

    // Extract the IDs from the view models.. Now a list of primitive types..
    var departmentIds = vmDept.Select(x => x.DeptId).ToList();
    

    然后在您的选择语句中...

    ..
    where departmentIds.Contains(id=> id == ers.org_assigneddept)
    ..
    

    【讨论】:

    • 答案的第一部分确定了问题的原因是正确的。但是,Any 的建议用法翻译不同,要获得 IN (...) 翻译,它应该使用 Contains (where departmentIds.Contains(ers.org_assigneddept)
    • 非常感谢您的回答。它工作得很好。我已经使用包含来获得结果。使用 Contains() 和 Any() 之间是否有任何显着差异。
    • 是的,很好,因为它是一个表达式,用于检查 ID 集合与它应该是 .Contains 的实体的 ID。更新答案。 .contains 和 .Any 之间的区别可以在这里找到:stackoverflow.com/questions/23526773/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多