Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in using PredicateBuilder

I need to know about using PredicateBuilder. On almost every example of how to use it, they show the code as follows:

var predicate = PredicateBuilder.True<employee>();

if (!string.IsNullOrEmpty(txtAddress.Text))
   predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
    predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
    predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
    predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));

EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
grdEmployee.DataSource = emp.ToList();
grdEmployee.DataBind();

What is that Employee object, the one between the greater than and less than brackets? I have racked my brains on that one. I am using Linq to SQL entities and I get compile errors when I try this myself. I think the errors are something like:

"Cannot cast from a Linq table to..."

I am a beginner. Please forgive me for asking what may be an obvious thing. Thank you.

like image 278
Edgar Cohen Avatar asked Nov 07 '12 00:11

Edgar Cohen


1 Answers

As @MatsRietdijk stated in the comments section, this is generics being used. Basically, with generics you can create a method that will operate on a type/class ("employee" in this instance) that is unknown (although you can control this with the where statement).

If you were to change the employee type for some other type (e.g. customer), then the properties available in the lambda expressions would also be different, based upon whatever properties were publically exposed. For example:

var predicate = PredicateBuilder.True<customer>();

// There is no "CustomerName" property from employee, but there is for customer objects
if (!string.IsNullOrEmpty(txtName.Text))
    predicate = predicate.And(e1 => e1.CustomerName.Contains(txtName.Text));
like image 99
Alexander Avatar answered Nov 01 '22 00:11

Alexander