Dynamic Linq OR with int and string

c# dynamic-linq linq

Question

I have a very simple query that would look like this

select      *
from        job
where       jobId like '%23%'
or title    like '%23%'

I need to be able to replicate this using dynamic Linq

The closest i've come to is this, but it doesn't work

.Where("@0.Contains(jobId) or title.Contains(@0)", "23");

Has anyone got a solution to this, ideally I would like it to do a like on both int's and strings

addendum based on comments

The error is:

An exception of type 'System.Linq.Dynamic.ParseException' occurred in System.Linq.Dynamic.dll but was not handled in user code Additional information: No applicable method 'Contains' exists in type 'String'

The jobId field is an int, while title is a varchar.

1
2
5/21/2015 8:19:40 AM

Accepted Answer

Your query is nearly right:

.Where("@0.Contains(jobId.ToString()) or title.Contains(@0)", "23")

Entity Framework (I hope you are using it) correctly changes jobId.ToString() to CAST( [Extent1].[Id] AS nvarchar(max))... It then uses a CHARINDEX instead of a LIKE, but this isn't a problem.

The query I get, with Entity Framework 6.1.3 on SQL Server is:

SELECT 
    [Extent1].[jobId] AS [jobId], 
    [Extent1].[title] AS [title]
    FROM [dbo].[job] AS [Extent1]
    WHERE (( CAST(CHARINDEX( CAST( [Extent1].[jobId] AS nvarchar(max)), N'23') AS int)) > 0) OR ([Extent1].[title] LIKE N'%23%')
6
5/21/2015 4:45:37 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow