简体   繁体   English

实体框架-> Execute和LIKE子句

[英]Entity Framework -> Execute and LIKE clause

I am having a little problem when passing parameters that need to perform a like through to my stored procedures. 将需要执行类似操作的参数传递到存储过程时,我遇到了一个小问题。

This is the code I have so far is as follows: 这是我到目前为止的代码如下:

using (GIDSEntities db = new GIDSEntities())
            {
                SqlParameter tvpClientList = new SqlParameter("@CorporateClientList", dtCompanies);
                tvpClientList.TypeName = "TravellerTracking.ClientIdList";
                SqlParameter pFromDate = new SqlParameter("@FromDate", fDate);
                SqlParameter pToDate = new SqlParameter("@ToDate", tDate);
                SqlParameter pLocation = new SqlParameter("@Location", "%" + location + "%");
                SqlParameter pTrains = new SqlParameter("@Trains", "%" + trains + "%");
                List<RailData> international = db.Database.SqlQuery<RailData>("exec TravellerTracking.InternationalRail @FromDate, @ToDate, @CorporateClientList, @Location, @Trains", pFromDate, pToDate, tvpClientList, pLocation, pTrains).ToList();
                Rail.AddRange(international);
            }

My stored procedure where clause looks like this: 我的存储过程where子句如下所示:

WHERE ((router LIKE CASE WHEN @Location = '%%' THEN router ELSE @Location END)
AND
    ((@Trains = '%%' AND trains = trains) OR trains LIKE @Trains))

As you can see I have tried writing the SQL differently to allow for nothing being passed by the user and something being passed. 如您所见,我尝试以不同的方式编写SQL,以允许用户不传递任何内容和传递某些内容。

Nothing I seem to do either in C# or SQL seems to work, does anyone have experience with this or a solution? 我似乎没有用C#或SQL进行的工作似乎都没有用,是否有人对此有经验或有解决方案?

Thanks Carl 谢谢卡尔

Pass the parameter without quotes: 传递不带引号的参数:

SqlParameter pTrains = new SqlParameter("@Trains", trains);

In the stored procedure you declare it like this: 在存储过程中,您需要这样声明:

@Trains varchar(100) = NULL

And use it in the query like this: 并在查询中像这样使用它:

AND (trains LIKE @Trains + '%' OR @Trains IS NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM