具有整数和字符串的动态Linq OR [英] Dynamic Linq OR with int and string

查看:93
本文介绍了具有整数和字符串的动态Linq OR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的查询,看起来像这样

I have a very simple query that would look like this

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

我需要能够使用动态Linq复制此

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");

有谁对此有解决方案,理想情况下,我希望它对int和string都做一个像

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

基于评论的附录

错误是:

System.Linq.Dynamic.dll中发生了类型'System.Linq.Dynamic.ParseException'的异常,但未在用户代码中处理附加信息:类型'String'中不存在适用的方法'Contains'

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'

jobId字段是int,而titlevarchar.

推荐答案

您的查询几乎是正确的:

Your query is nearly right:

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

实体框架(我希望您正在使用它)正确地将jobId.ToString()更改为CAST( [Extent1].[Id] AS nvarchar(max)) ...然后使用CHARINDEX而不是LIKE,但这不是问题.

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.

在SQL Server上使用Entity Framework 6.1.3获得的查询是:

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

这篇关于具有整数和字符串的动态Linq OR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆