c# - SQL 语句的某些部分嵌套太深 c# EF 5

标签 c# sql linq entity-framework where-clause

我从 EF 5 得到以下异常: SQL 语句的某些部分嵌套太深。重写查询或将其分解为更小的查询。

这是我的查询:

String username = “test”;
IEnumerable<Int32> roles;
IEnumerable<Int32> applications;

cnx.Users.Where ( it =>
( userName != null ?  it.name = = userName : true )  &&
( !roles.Any () || roles.Contains ( it.role_id ) ) &&
( ! applications.Any () || applications.Contains ( it.application_id ) ) )
               .Count ();

Users 是一个简单的表。 角色和应用程序都是 IEnumerable 类型,可以为空。

如何更改我的查询,使其在 EF 5 (.Net 4.0) 中工作?

最佳答案

对我来说,userNamerolesapplications 是查询的参数,即数据来自您的应用程序,而不是来自数据库。在那种情况下,我会这样写查询:

IQueryable<User> query = cnt.Users;
if(userName != null)
    query = query.Where(x => x.name == userName)
if(roles.Any())
    query = query.Where(x => roles.Contains(x.role_id));
if(applications.Any())
    query = query.Where(x => applications.Contains(x.application_id))

var result = query.Count();

这更具可读性,并且不会在结果查询中包含不必要的困惑。

请注意,rolesapplications 不能表示另一个查询的未执行结果。 对于“未执行的结果”,我的意思是:

IEnumerable<Role> roles = context.Roles.Where(x => x = y);

关于c# - SQL 语句的某些部分嵌套太深 c# EF 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19002732/

相关文章:

c# - 覆盖全局操作过滤器

mysql - 选择现在和时间戳之间的差异小于 24 小时

SQL 约束最小值/最大值?

c# - LINQ 中的动态 where 子句?

C# LINQ,将多个for循环嵌套在一个foreach中的并行转换

c# - 将 SQL 的结果除以单独的 List <int>

c# - 为 VSTO 应用创建跨项目功能区

c# - Visual Studio F5 调试比附加到进程慢

c# - 这行 HTTP 代码的替代方案

sql - 如何在聚合函数 SQL Server 中有一个 where 子句