I have a screen in my project " Enquiry" where I user can perform 2 kinds of search.I cannot figure out how to do a "like" or "And or is null" in Linq to entity.
- Simple Search ( Search in all fields using "Like" operator)
- Advanced Advanced Search (Use "And" Operator)
So lets take these 3 ta开发者_运维技巧bles and make up a noddy example.
- Customer Table (CustomerID,Name,Surname)
- Address(AddressID,Street,City)
- CustomerOrder (OrderID,OrderName)
Basic search : this is how I would do it in Sql
SELECT TOP (100) C.Name,C.Surname,CA.Street,CA.City,CO.OrderName
FROM Customer C
LEFT JOIN CustomerAddress CA ON C.CustomerID=CA.CustomerID
LEFT JOIN CustomerOrders CO ON C.CustomerID=CA.CustomerID
WHERE (C.CustomerID LIKE '%' + @SearchText + '%'
OR C.Surname LIKE '%' + @SearchText + '%'
OR C.Name LIKE '%' + @SearchText + '%'
OR CA.Street LIKE '%' + @SearchText + '%'
OR CA.City LIKE '%' + @SearchText + '%'
OR CO.OrderName LIKE '%' + @SearchText + '%') )
Advanced Search
This my sql where clause
WHERE (C.CustomerID =@CustomerID or @CustomerID ISNULL
AND C.Surname =@Surname or @Surname ISNULL
AND C.Name=@Name or @Name ISNULL
AND CA.Street =@Street or @Street ISNULL
AND CA.City =@City or @City ISNULL
AND CO.OrderName =@OrderName or @OrderName ISNULL)
AND ((ModifiedDate BETWEEN ISNULL(convert(varchar,@FromDate,101),'01/01/1901')
AND ISNULL(convert(varchar,@ToDate,101),'12/31/9999'))
How do you do Likes or and or is null in entity framework?
thanks a lot!
For LIKE
, you can use Contains
, StartsWith
, or EndsWith
. For IS NULL
, use == null
.
Example:
var list = from p in Products
where (p.Description.Contains("v") && p.Description.StartsWith("C"))
|| p.MFRCode == "TOYOTA"
|| p.Universal == null
select p;
will cause EF to generate this SQL:
SELECT
[Extent1].[MFRCode] AS [MFRCode],
[Extent1].[MFRProductID] AS [MFRProductID],
[Extent1].[Universal] AS [Universal],
[Extent1].[Description] AS [Description]
FROM [dbo].[Products] AS [Extent1]
WHERE (([Extent1].[Description] LIKE N'%v%') AND ([Extent1].[Description] LIKE N'C%')) OR (N'TOYOTA' = [Extent1].[MFRCode]) OR ([Extent1].[Universal] IS NULL)
and produce these results:
Edit
I used LINQPad to generate these results. It's a great tool, free to use (there's an option to purchase an Intellisense feature), and definitely worth a look if you'd like to experiment with different LINQ queries and see the SQL that EF is generating (it's good for general LINQ experimentation and quickly trying out simple code as well).
int? customerID = null;
string surname = "abc";
var q = from c in oc.Customers
where (customerID == null || c.CustomerID == customerID)
&& (surname == null || c.Surname == surname)
select c;
精彩评论