I am trying to make a simple search method using LINQ to SQL in Visual Studio. In my database, I have the fields "Firstname" and "Lastname", and my search string is "name". How can I make a simple LINQ query which searches both fields?
In plain SQL I would do something like this:
SELECT (Firstname + Lastname) as 'Fullname'
FROM table
WHERE Fullname LIKE '%searchstring%'
The usual thing to do is this:
var users =
from user in db.Users
where user.FirstName.Contains(searchString) ||
user.LastName.Contains(searchString)
select user;
This however is not equivalent to your SQL query. The following is equivalent:
var users =
from user in db.Users
let fullName = user.FirstName + user.LastName
where fullName.Contains(searchString)
select user;
var result = from p in db.Table
let fullname = p.FirstName + " " + p.Lastname
where fullname.Contains(searchString)
select new { Fullname = fullname };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With