Thanks, this works, but I don't know why it makes a difference using .ToLower??? surely this just makes all the query text and the searchable text lower case? if all my query is in the correct case, my original query should have worked anyway?
I compare the lower case values for the properties of a customer with the lower case value of the search string which means the search is not case sensitive.
MangoMM
Member
65 Points
55 Posts
Linq Search more than one column in database table
Apr 12, 2012 08:57 PM|LINK
I have the following code to search for a customer by their name.
I wish to modify this code to allow a search for a customer by:
// // POST: /CustomerManager/Search?q=smith public ActionResult Search(string q) { q = HttpUtility.HtmlEncode(q); if (q == "") return RedirectToAction("Index"); else { var customers = db.Customers.Include("CustomerTypes").Where(a => a.Name.Contains(q) || q == null).Take(10); return View(customers); } }I have tried the following with no luck:
var customers = db.Customers.Include("CustomerTypes").Where(a => a.Name.Contains(q) || a.Email.Contains(q) || a.CompanyName.Contains(q) || q == null).Take(10);contains Linq search
sravanisrav
Member
470 Points
107 Posts
Re: Linq Search more than one column in database table
Apr 13, 2012 06:42 AM|LINK
Hello,
Here is a sample example to search the database table and fetch the records in grid view using Linq:
viewstate contains Linq sorting search
Thanks & Regards
Sravani
mm10
Contributor
6409 Points
1184 Posts
Re: Linq Search more than one column in database table
Apr 13, 2012 09:15 AM|LINK
Try this, it searches in all columns (Name, Email, CompanyName) for the string q and all records if q is null or empty:
q = q.ToLower();
var customers = db.Customers.Include("CustomerTypes").Where(a => a.Name.ToLower().Contains(q) || a.Email.ToLower().Contains(q) || a.CompanyName.ToLower().Contains(q) || string.IsNullOrEmpty(q)).Take(10);
MangoMM
Member
65 Points
55 Posts
Re: Linq Search more than one column in database table
Apr 13, 2012 12:05 PM|LINK
thanks for your reply sravanisrav, but I don't know what you are doing here. I don't know how your example helps me.
MangoMM
Member
65 Points
55 Posts
Re: Linq Search more than one column in database table
Apr 13, 2012 12:07 PM|LINK
Thanks, this works, but I don't know why it makes a difference using .ToLower??? surely this just makes all the query text and the searchable text lower case? if all my query is in the correct case, my original query should have worked anyway?
mm10
Contributor
6409 Points
1184 Posts
Re: Linq Search more than one column in database table
Apr 13, 2012 12:08 PM|LINK
I compare the lower case values for the properties of a customer with the lower case value of the search string which means the search is not case sensitive.
MangoMM
Member
65 Points
55 Posts
Re: Linq Search more than one column in database table
Apr 13, 2012 12:11 PM|LINK
Thanks again MM10.