llnq SqlMethods like
http://www.cnblogs.com/freeliver54/archive/2009/09/05/1560815.html
http://www.cnblogs.com/chen1388/archive/2010/03/12/1684450.html
http://www.cnblogs.com/hantianwei/archive/2011/04/08/2009768.html
本文转自:http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx
原文如下:
As a response for customer's question, I decided to write about using Like Operator in Linq to SQL queries.
Starting from a simple query from Northwind Database;
var query = from c in ctx.Customers
where c.City == "London"
select c;
The query that will be sent to the database will be:
SELECT CustomerID, CompanyName, ...
FROM dbo.Customers
WHERE City = [London]
There are some ways to write a Linq query that reaults in using Like Operator in the SQL statement:
1. Using String.StartsWith or String.Endswith
Writing the following query:
var query = from c in ctx.Customers
where c.City.StartsWith("Lo")
select c;
will generate this SQL statement:
SELECT CustomerID, CompanyName, ...
FROM dbo.Customers
WHERE City LIKE [Lo%]
which is exactly what we wanted. Same goes with String.EndsWith.
But, what is we want to query the customer with city name like "L_n%"? (starts with a Capital 'L', than some character, than 'n' and than the rest of the name). Using the query
var query = from c in ctx.Customers
where c.City.StartsWith("L") && c.City.Contains("n")
select c;
generates the statement:
SELECT CustomerID, CompanyName, ...
FROM dbo.Customers
WHERE City LIKE [L%]
AND City LIKE [%n%]
which is not exactly what we wanted, and a little more complicated as well.
2. Using SqlMethods.Like method
Digging into System.Data.Linq.SqlClient namespace, I found a little helper class called SqlMethods, which can be very usefull in such scenarios. SqlMethods has a method called Like, that can be used in a Linq to SQL query:
var query = from c in ctx.Customers
where SqlMethods.Like(c.City, "L_n%")
select c;
This method gets the string expression to check (the customer's city in this example) and the patterns to test against which is provided in the same way you'd write a LIKE clause in SQL.
Using the above query generated the required SQL statement:
SELECT CustomerID, CompanyName, ...
FROM dbo.Customers
WHERE City LIKE [L_n%]
SqlMethods.Like还有一个参数,叫escape Character,其将会被翻译成类似下面的语句。
SELECT columns FROM table WHERE
column LIKE '%\%%' ESCAPE '\'
escape 是因为某字段中含有特殊字符,比如%,_ [ ]这些被用作通配符的。这时就要用到Escape了。这是sql server的事情了。
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET