Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Contains doesn't work correct with NTEXT and SQL CE #652

Open
bjarnef opened this issue Dec 14, 2021 · 2 comments
Open

Contains doesn't work correct with NTEXT and SQL CE #652

bjarnef opened this issue Dec 14, 2021 · 2 comments

Comments

@bjarnef
Copy link

bjarnef commented Dec 14, 2021

If generating a SQL query using Contains() on a db column of type NTEXT the query breaks on SQL CE using NPoco v4.0.2

Sql<ISqlContext> sql = Sql();

sql.Select("*")
   .From<ReviewDto>()
   .Where<ReviewDto>(x => x.StoreId == storeId);

if (!string.IsNullOrWhiteSpace(searchTerm))
{
    sql.Where<ReviewDto>(x =>
        x.Title.Contains(searchTerm) ||
        x.Name.Contains(searchTerm) ||
        x.Email.Contains(searchTerm) ||
        x.Body.Contains(searchTerm) // Body is of type NTEXT on SQL CE and NVARCHAR(MAX) on MSSQL 
    );
}

sql.OrderByDescending<ReviewDto>(x => x.CreateDate);

var page = _uow.Database.Page<ReviewDto>(pageNumber, pageSize, sql);

which generate the following SQL query:

SELECT *
FROM [review]
WHERE (([review].[storeId] = @0))
AND ((((upper([review].[title]) LIKE upper(@1) OR upper([review].[name]) LIKE upper(@2)) OR upper([review].[email]) LIKE upper(@3)) OR upper([review].[body]) LIKE upper(@4)))
ORDER BY ([review].[createDate]) DESC

If I remove the wrapping upper() function around [review].[body] it works.
Alternatively cast the field, cast or convert on [review].[body] to nvarchar before using upper() function.

@bjarnef
Copy link
Author

bjarnef commented Dec 15, 2021

For now I use the following workaround:

sql.Where($"( upper({ReviewDto.TableName}.{SqlSyntax.GetQuotedColumnName("title")}) LIKE upper(@term) " +
   $"OR upper({ReviewDto.TableName}.{SqlSyntax.GetQuotedColumnName("name")}) LIKE upper(@term) " +
   $"OR upper({ReviewDto.TableName}.{SqlSyntax.GetQuotedColumnName("email")}) LIKE upper(@term) " +
   $"OR upper(convert(nvarchar(4000), {ReviewDto.TableName}.{SqlSyntax.GetQuotedColumnName("body")})) LIKE upper(@term))", new { term = $"%{searchTerm}%" });

instead of:

sql.Where<ReviewDto>(x =>
    x.Title.Contains(searchTerm) ||
    x.Name.Contains(searchTerm) ||
    x.Email.Contains(searchTerm) ||
    x.Body.Contains(searchTerm)
);

@schotime
Copy link
Owner

Tricky one this, cause if you want to do a case insensitive like you need the upper. And the fact you have to cast it, means if it really had ntext/nvarchar(max) data in it, it wouldn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants