我从 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) 中工作?
最佳答案
对我来说,userName
、roles
和 applications
是查询的参数,即数据来自您的应用程序,而不是来自数据库。在那种情况下,我会这样写查询:
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();
这更具可读性,并且不会在结果查询中包含不必要的困惑。
请注意,roles
和applications
不能表示另一个查询的未执行结果。
对于“未执行的结果”,我的意思是:
IEnumerable<Role> roles = context.Roles.Where(x => x = y);
关于c# - SQL 语句的某些部分嵌套太深 c# EF 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19002732/