Dynamic Linq OR with int and string

我是研究僧i 提交于 2019-12-24 03:51:04

问题


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:


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%')


来源:https://stackoverflow.com/questions/30367815/dynamic-linq-or-with-int-and-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!