Optional Parameters in EntityFrameWork query

2k views Asked by At

My method signatures are as following. Only Id is mandatory, all other three parameters are option. I need to handle this in where clause. If optional ones are present then i need to add them to where clause otherwise query should be built on Id and whatever is available from Optional parameters

Secondly can we use rowVersion in comparison as specified in the query below. (rowVersion in Sql Server is a time stamp)

GetRecords(int  Id, int[] LocationId = null, int PayrollNo = 0, byte[] rowVersion=null)

 {

     var result = this.context.employees.where(x=>x.Id == id && LocationId.Contains(x.locationId) && x.payrollNo ==PayrollNo && x.rowVersion >  rowVersion);

}

any help would be much appreciated.

1

There are 1 answers

2
Steve Greene On

Try this:

GetRecords(int  Id, int[] LocationId = null, int PayrollNo = 0, byte[] rowVersion=null)

 {

     var result = this.context.employees.where(x=>x.Id == id);
     if (LocationId != null)
         result = result.Where(x=>LocationId.Contains(x.locationId));
     if (PayrollNo > 0)
         result = result.Where(x=>x.payrollNo == PayrollNo);
     if (rowVersion != null)
         result = result.Where(x=>x.rowVersion >  rowVersion);

}