NotSupportedException:无法在LINQ查询中创建常数值



我有以下代码,该代码返回不支持的异常。现在我不确定为什么。

所有四个子查询(变量创建者,公司,公司用户和位置使用者(返回数据库对象,而我仅在子查询之后调用Tolist((。

错误发生在代码的最后一行,并说:

Unable to create a constant value of type 'Data.CRM_UserLocatie'

是什么导致此错误,我该如何解决?

            var creator = Db.UserTable.Include(u => u.UserDataTable).SingleOrDefault(u => u.UserPk == userId);
            if (creator == null)
                return null;
            var companies= Db.CompanyTable.Where(w => creator.UserLocation.Any(a => a.LocationTable.CompanyId== w.CompanyId|| a.LocationTable.CompanyTable.ParentId == w.CompanyId)).Select(s => s.CompanyId);
            var companyUsers = (from u in Db.UserLocation
                join l in Db.LocationTable on u.LocationId equals l.LocationId 
                where companies.Contains(l.CompanyId?? 0)
                select u.UserId);         
            var locationUsers = (from l in Db.LocationTable 
                                join ul in Db.UserLocationon l.LocationId equals ul.LocatieId 
                                join u in Db.UserTable on ul.UserId equals u.UserId 
                                where companies.Contains(l.companyId?? 0)
                                select u.UserId);
            var totalUsers = companyUsers.Union(locationUsers );
            var employees = Db.UserTable.Where(u => u.RoleId == participantId && u.Actief && totalUsers.Select(c => c).Contains(u.UserId));
            return employees.ToList().Select(m => new User(m)).ToList();

该错误主要是因为您将LINQ与Linq与对象混合到实体,因此尝试将实体与内存中的对象进行比较。

linq到实体仅接受基于集合的contrains((方法或enumoble.contains((扩展。WHERE x IN (const_1, const_2, ..., const_n)在运行时。

您要么找到一个查询,该查询不需要预加载任何数据,要么在使用基于集合的contains((方法之前,将相关数据预加载到列表或原始阵列中。

也可以隐式将Linq的片段运行到对象并使用Linq中的结果对实体查询,但是为了避免副作用,我不建议它。

最新更新