您好我正在寻找编写动态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; }
使用像这样的高阶函数可能会让你感到困惑,如果你对它不太满意,那么如果你没有做很多这样的查询,你可能会想要坚持更长但更简单的代码.