Hi I am looking for best method for writing Dynamic LINQ query.
I have a function like
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;
}
we can also write db.Students.where(predicate)
or
a query like
var students = from s in db.students where s.Name.Contains(Name)
s.ID.Equals(id)
//and so on....
So will this method works if i don’t pass ID (i.e. Null)?
is proper way for all the datatypes?
The point is function can have all null values as a parameter for equivalence of select * from statement.
can any one help me to build best query with sample code?
Okay, it’s not entirely clear what you want, but if you’re trying to only add where clauses for the parameters which are non-null, you could do:
I haven’t tried that, and it’s possible that LINQ to SQL would get confused by the code to find the value of the nullable value types. You may need to write code like this:
It’s worth trying the simpler form first though 🙂
Of course, all this gets a bit irritating. A helpful extension method could make life more concise:
You’d then use it like this:
Using a higher order function like this could get confusing if you’re not really comfortable with it though, so if you’re not doing very many queries like this you might want to stick with the longer but simpler code.