arrays - 带有 int 数组参数的 EF ExecuteSqlCommand

标签 arrays entity-framework asp.net-mvc-4

我在尝试传递 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/

相关文章:

c - 在 C 中的特定位置传递数组

asp.net - 为什么我必须在我的 UI 项目中引用 EF?

asp.net-mvc - 如何将 HTML 保存到数据库并正确检索

c# - 设置单元测试以使用 Unity 测试 Controller

php array_intersect 关联和索引数组

arrays - char 之前的预期表达式

javascript - 动态搜索值并创建变量的脚本?

json - Entity Framework : How to map a complex object to a single varchar column (i. e。以序列化形式保存)?

c# - EF Core 中 SqlFunctions 的等效项

c# - 从同一服务器上的 MVC 调用 WCF 服务时出现 SocketException