IN 语句中的数据上下文 ExecuteCommand 参数

发布于 2024-07-18 10:08:42 字数 466 浏览 5 评论 0原文

使用 IN 从 C# LinQ 到 sql 数据上下文运行自定义 sql 语句的最佳方法是什么? 我已经尝试过:

db.ExecuteCommand(
   "UPDATE tblCard SET used = 1 WHERE id IN ({0}) AND customer_id = {1}",
   Request.Form["ids"], customer_id
);

对于通过表单传递的 1 项来说这是可以的,但是如果我通过例如“2,1”发布,那么我会收到 sqlclient 异常:

将 nvarchar 值“2,1”转换为数据类型 int 时转换失败。

如果我使用 string.format 插入参数,它可以正常工作,但显然这对 sql 注入是开放的。

What is the best way to run a custom sql statement using IN from a C# LinQ to sql datacontext? I have tried:

db.ExecuteCommand(
   "UPDATE tblCard SET used = 1 WHERE id IN ({0}) AND customer_id = {1}",
   Request.Form["ids"], customer_id
);

Which is fine for 1 item passed through the form, but if i get posted through for example "2,1" then I get a sqlclient exception:

Conversion failed when converting the nvarchar value '2,1' to data type int.

If instead I use string.format to insert the parameter it works fine, but obviously this is open to sql injection.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百合的盛世恋 2024-07-25 10:08:42

LINQ-to-SQL 不使用串联; 这将是以下形式的 TSQL 查询:

WHERE id IN (@p0) 

@p0 设置为 '123,456,789'

对于常规 LINQ,您可以使用 Contains。 使用ExecuteQuery有几个选项; 例如,您可以“按原样”传入 CSV,并使用 UDF 在数据库中拆分它,然后加入其中:

UPDATE c SET c.used = 1
FROM dbo.SplitCsv({0}) udf
INNER JOIN tblCard c
        ON c.Id = udf.Value
       AND c.Customer_ID = {1}

其中 dbo.SplitCsv 是许多此类“拆分”之一“ udf 可在互联网上找到。

LINQ-to-SQL doesn't use concatenation; that will be a TSQL query of the form:

WHERE id IN (@p0) 

with @p0 set to '123,456,789'.

With regular LINQ you could use Contains. With ExecuteQuery there are a few options; you could, for example, pass in the CSV "as is", and use a UDF to split this at the database, and join to it:

UPDATE c SET c.used = 1
FROM dbo.SplitCsv({0}) udf
INNER JOIN tblCard c
        ON c.Id = udf.Value
       AND c.Customer_ID = {1}

Where dbo.SplitCsv is one of the many such "split" udfs available on the internet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文