Linq to SQL - How to build up a where clause dynamically
Posted: Tue 19 Feb 2013 14:44
Hi all,
I've been chipping away at this problem all day and I can't really make much progress. So thought I would post here to see if anyone had any ideas.
The problem
I'm building a search form to allow my users to search a staff directory. So users can search by staff number, first name or last name. So any mixture of these three fields (and possibly more in the future) are needed. I also need to allow partial matches to be found e.g. Searching Sm* would find Smith, Smooth, Smoke etc.
The code so far
In this working example I created it does return data but only when searching on the staff number. I'm not sure how to effectively build up a dynamic 'where' clause with Linq to SQL. I did initially try out building up a SQL style string e.g. WHERE c.UserID = 'XYZ' AND c.LastName Like '%sm%' - but passing as a variable in to the linq's where clause didn't work.
So I'm hoping there are some of you out there in the wider community who have already done what I'm trying to do and be able to share your insight and a clear example?
Thanks!
I've been chipping away at this problem all day and I can't really make much progress. So thought I would post here to see if anyone had any ideas.
The problem
I'm building a search form to allow my users to search a staff directory. So users can search by staff number, first name or last name. So any mixture of these three fields (and possibly more in the future) are needed. I also need to allow partial matches to be found e.g. Searching Sm* would find Smith, Smooth, Smoke etc.
The code so far
Code: Select all
TKDataContext db = new TKDataContext();
Table<Staff_Table> _items = db.GetTable<Staff_Table>();
List<StaffDirectory> menulist = (from c in _items
where c.UserId == varStaffNumber
select new StaffDirectory()
{
UserId = c.UserId,
FirstName = c.FirstName,
MiddleName = c.MiddleName,
LastName = c.LastName,
EMAILADDRESS = c.EMAILADDRESS,
COUNTRY = c.COUNTRY
}).ToList();
return menulist;
So I'm hoping there are some of you out there in the wider community who have already done what I'm trying to do and be able to share your insight and a clear example?
Thanks!
