加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

数组 – 带有int数组参数的EF ExecuteSqlCommand

发布时间:2020-12-16 06:27:21 所属栏目:asp.Net 来源:网络整理
导读:尝试使用类型数组int传递参数时遇到问题.到目前为止我做了什么,但两种方法都失败了. 方法1(失败): int[] CategoryArray;CategoryArray = new int[userItem.ListItemId.Count()];int i=0;foreach (int catID in userItem.ListItemId){ CategoryArray[i] = ca
尝试使用类型数组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})",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})",userItem.ListItemId),userItem.UserId));

这样,string.format调用应该将您的int列表作为文本嵌入,然后将其传递给ExecuteSqlCommand方法,该方法将处理用户ID.

放弃上述方法可以被Sql Injection攻击利用.如果您不控制用于构建要删除的ID列表的数据源,请不要使用它.一般来说,我建议不要使用这种方法,除非你真的知道它是如何使用的,你确定没有什么不好的事情发生(你真的永远不会……)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读