zoukankan      html  css  js  c++  java
  • Linq to SQL Like Operator(转)

    http://www.cnblogs.com/freeliver54/archive/2009/09/05/1560815.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%]

    Enjoy!

     

  • 相关阅读:
    就打排序算法总结
    php 垃圾回收机制写时复制和引用计数
    zend studio 使用断点调试
    SiteServer 迁移至 Windows 2008 R2 问题汇总
    [项目改造中的点滴]C#中IDataReader和DataSet的区别与使用场景
    顺序分支知识总结
    我的第一篇博客
    [原创]删除GRUB引导恢复Windows引导,不用下载任何工具
    在C++builder中使用正则表达式,非boost库,简单!~
    SQL 存储过程优化经验
  • 原文地址:https://www.cnblogs.com/quietwalk/p/2225600.html
Copyright © 2011-2022 走看看