asp.net – 构建动态LINQ查询的最佳方法
发布时间:2020-12-16 04:20:01 所属栏目:asp.Net 来源:网络整理
导读:您好我正在寻找编写动态LINQ查询的最佳方法. 我有一个像这样的功能 public IQueryableStudent FindByAllStudents(int? id,string Name,int? CourseID,bool? IsActive) // like this way,all field values are passed { // code for compairision return db.S
您好我正在寻找编写动态LINQ查询的最佳方法.
我有一个像这样的功能 public IQueryable<Student> FindByAllStudents(int? id,string Name,int? CourseID,bool? IsActive) // like this way,all field values are passed { // code for compairision return db.Student; } 我们也可以写db.Students.where(谓词) 要么 像这样的查询 var students = from s in db.students where s.Name.Contains(Name) s.ID.Equals(id) //and so on.... 如果我不传递ID(即Null),这种方法会起作用吗? 关键是函数可以将所有空值作为select * from语句等价的参数. 任何人都可以帮助我用示例代码构建最佳查询? 解决方法
好吧,它并不完全清楚你想要什么,但是如果你只想添加非null的参数where子句,你可以这样做:
public IQueryable<Student> FindByAllStudents (int? id,string name,int? courseID,bool? isActive) { IQueryable<Student> query = db.Student; if (id != null) { query = query.Where(student => student.ID == id.Value); } if (name != null) { query = query.Where(student => student.Name.Contains(name)); } if (courseID != null) { query = query.Where(student => student.CourseID == courseID.Value); } if (isActive != null) { query = query.Where(student => student.IsActive == isActive.Value); } return query; } 我没有尝试过,并且LINQ to SQL可能会被代码混淆以找到可空值类型的值.您可能需要编写如下代码: if (courseID != null) { int queryCourseID = courseID.Value; query = query.Where(student => student.CourseID == queryCourseID); } 首先尝试更简单的形式值得:) 当然,这一切都有点恼人.一种有用的扩展方法可以使生活更简洁: public static IQueryable<TSource> OptionalWhere<TSource,TParameter> (IQueryable<TSource> source,TParameter? parameter,Func<TParameter,Expression<Func<TSource,bool>>> whereClause) where TParameter : struct { IQueryable<TSource> ret = source; if (parameter != null) { ret = ret.Where(whereClause(parameter.Value)); } return ret; } 然后你就像这样使用它: public IQueryable<Student> FindByAllStudents (int? id,bool? isActive) { IQueryable<Student> query = db.Student .OptionalWhere(id,x => (student => student.ID == x)) .OptionalWhere(courseID,x => (student => student.CourseID == x)) .OptionalWhere(isActive,x => (student => student.IsActive == x)); if (name != null) { query = query.Where(student => student.Name.Contains(name)); } return query; } 使用像这样的高阶函数可能会让你感到困惑,如果你对它不太满意,那么如果你没有做很多这样的查询,你可能会想要坚持更长但更简单的代码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 带密码的.NET核心分布式Redis缓存
- 实体框架 – 使用EF和WebAPI,如何返回一个ViewModel并支持I
- asp.net-mvc – Bootstrap模式表单在提交后不会关闭
- asp.net – 如何将SQL用户定义的函数添加到实体框架?
- asp.net-mvc – 没有注册默认实例,无法自动确定类型
- asp.net – 什么是确定我的视图状态的好方法?
- asp.net-mvc – 在VS2013中将Azure单点登录添加到现有的MVC
- Asp.net形成认证cookie,不符合IIS7超时
- asp.net-mvc – “信号量超时期限已过期”SQL Azure
- asp.net-mvc – 如何在asp.net mvc 3中使用@html.actionlin