We can pass LINQ conditions dynamically as parameter, Lets consider simple example to get Single property and multiple properties by condition. We can use this for Generic Repository Pattern also.
Implementation below,
public Student GetSingleObjectByCondition(System.Func<Student, bool> predicate)
Implementation below,
public Student GetSingleObjectByCondition(System.Func<Student, bool> predicate)
{
var result = default(Student);
using (var efContext = new DbContext())
{
result = efContext.Students.FirstOrDefault(predicate);
}
return result;
}
public List<Student> GetMultipleObjectsByCondition(Func<Student, bool> predicate)
{
var result = default(List<Student>);
using (var efContext = new DbContext())
{
result = efContext.Students.Where(predicate).ToList<Student>();
}
return result;
}
}
How to call the method,
Func<Student, bool> selector = str => str.Name == "Balaji";
How to call the method,
Func<Student, bool> selector = str => str.Name == "Balaji";
var student =
_studentRepository.GetSingleObjectByCondition(selector);
Func<Student, bool> selector = str => str.Rank <= 5;
var students = _studentRepository.GetMultipleObjectsByCondition(selector);