开发者

How do I prevent the Entity Framework from escaping my Regex?

开发者 https://www.devze.com 2022-12-14 14:34 出处:网络
Put simply... in plain SQL I would do this: SELECT * FROM [Products] WHERE [Description] LIKE \'%[0-9]%\'

Put simply... in plain SQL I would do this:

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

In Linq to Entities I do this:

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

But I end up with this:

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

Which escapes my attempt at SQL regex.

Any ideas how to circumvent this?

Edit

I should add that I am using the Ent开发者_开发问答ity Framework with it's SQL Provider (is that right?) and I am attempting to have the work done on an IQueryable i.e. not have to bring all the rows into .NET before I can run the Regex


You can use Like in the query:

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

But this only works with LINQ to SQL not LINQ to Entities however you are showing the conversion of the LINQ to an SQL statement so I'm guessing that you're using LINQ to SQL. If not, then just use a Regex expression in the Where.


Off the top of my head:

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

I haven't tested this but it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消