我在尝试传递 int 类型数组的参数时遇到问题。到目前为止我所做的事情如下,但两种方法都失败了。
方法1(失败):
int[] CategoryArray;
CategoryArray = new int[userItem.ListItemId.Count()];
int i=0;
foreach (int catID in userItem.ListItemId)
{
CategoryArray[i] = catID;
i++;
}
db.Database.ExecuteSqlCommand("delete from SupportRegion where UserId={0} and CategoryID not in ({1})", userItem.UserId, CategoryArray);
方法2(也失败):
db.Database.ExecuteSqlCommand("delete from SupportRegion where UserId={0} and CategoryID not in ({1})", userItem.UserId, String.Join(",", userItem.ListItemId));
如何才能将参数定义为整数数组?
非常感谢
最佳答案
第一种情况不起作用,因为数据库不理解 int 数组的含义。我不知道第二个示例中的“失败”意味着什么,但我想 Sql Server 无法将字符串转换为 int。我相信服务器端发生的情况是查询被转换为类似这样的内容(注意引号):
delete from SupportRegion where UserId={0} and CategoryID not in ('1, 2, 3')
因为您传递的参数是一个字符串。但是,CategoryID 列不是字符串,传递的参数无法转换为 int。
我认为您可以尝试使用表值参数,但它看起来像 setting it up有点丑。
根据要删除的实体数量,最安全的做法可能是将实体带到客户端,将要删除的实体标记为已删除,然后调用 SaveChanges()。
另一种解决方法是正确设置命令文本(请参阅下面的免责声明):
db.Database.ExecuteSqlCommand(
string.Format(
"delete from SupportRegion where UserId={{0}} and CategoryID in ({0})",
String.Join(",", userItem.ListItemId),
userItem.UserId));
这样 string.format 调用应该将您的整数列表作为文本嵌入,然后将其传递给 ExecuteSqlCommand 方法,该方法将处理用户 ID。
免责声明 上述方法可能会被 Sql 注入(inject)攻击所利用。如果您无法控制用于构建要删除的 ID 列表的数据源,则切勿使用它。一般来说,我建议不要使用这种方法,除非你真的知道它是如何使用的,并且你确定没有什么不好的事情发生(你真的永远不会……)
关于arrays - 带有 int 数组参数的 EF ExecuteSqlCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558360/