代码之家  ›  专栏  ›  技术社区  ›  joshcomley

如何防止实体框架转义regex?

  •  1
  • joshcomley  · 技术社区  · 15 年前

    简单地说…在普通的sql中,我会这样做:

    SELECT * FROM [Products] WHERE [Description] LIKE '%[0-9]%'
    

    在linq to entities中,我这样做:

    Products.Where(p => p.Description.Contains("[0-9]"))
    

    但我最终得到的是:

    -- Region Parameters
    DECLARE @p0 NVarChar(8) SET @p0 = '%~[0-9]%'
    -- EndRegion
    SELECT ...
    FROM [Products] AS [t0]
    WHERE [t0].[Description] LIKE @p0 ESCAPE '~'
    

    这就避免了我在sql regex上的尝试。

    有什么办法可以避开这个吗?

    编辑

    我应该补充一点,我将实体框架与它的sql提供程序一起使用(对吗?)我正在尝试在iqueryable上完成工作,也就是说,在运行regex之前,不必将所有行都带到.net中。

    1 回复  |  直到 15 年前
        1
  •  2
  •   James Keesey    15 年前

    您可以在查询中使用like:

    using System.Data.Linq.SqlClient;
    ...
    var query = from p in Products
                where SqlMethods.Like(p.Description, "%[0-9]%")
                select p;
    

    但是这只适用于linq到sql而不是linq到实体,但是您显示了linq到sql语句的转换,所以我猜您使用的是linq到sql。如果不是,那么只需在where中使用regex表达式。


    从我的头顶上:

    RegEx pattern = new RegEx("[0-9]");
    ...
    var query = from p in Products
                where patter.IsMatch(p.Description)
                select p;
    

    我还没测试过,但应该能用。