gpt4 book ai didi

c# - 将条件参数传递给 Database.SqlQuery

转载 作者:行者123 更新时间:2023-11-30 20:22:42 34 4
gpt4 key购买 nike

我一直在执行以下操作以使用我的 sql 查询传递参数:

var retval = context.MyObject.SqlQuery(sql.ToString(),
new SqlParameter("@ProductId", productId),
new SqlParameter("@CustomerId", customerId)).ToList();

我遇到了这样一种情况,在我的 sql 字符串中并不总是使用 @CustomerId。这意味着我使用 if 语句来添加 (Where p.CustomerId = @CustomerId) 或将其保留。

我意识到我现在无法将我的参数直接传递给 SqlQuery 函数。相反,我必须创建一个对象参数列表,然后将其传入:

        SqlParameter param1 = new SqlParameter("@ProductId", productId);
SqlParameter param2 = new SqlParameter("@CustomerId", customerId);
object[] parameters = new object[] { param1, param2 };

如何才能使用 if 语句将 CustomerId 参数添加到我的参数数组中?

最佳答案

您可以对此编辑您的查询

SELECT * FROM Product p 
WHERE
p.ProductId = @ProductId
AND (@CustomerId IS NULL OR p.CustomerId = @CustomerId)

如果不使用,则将 DBNull.Value 传递给 @CustomerId

关于c# - 将条件参数传递给 Database.SqlQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30848244/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com