简体   繁体   English

在实体框架中删除多行

[英]Delete multiple rows in Entity Framework

I am trying to delete multiple rows in EF5 and I'm using the following code sample 我正在尝试删除EF5中的多行,并且正在使用以下代码示例

string TestId = "12,23";
Context.Database.ExecuteSqlCommand("DELETE FROM TEST WHERE TESTID IN (@Params)", new SqlParameter("Params", TestId));

How do I pass SqlParameter for IN ? 如何为IN传递SqlParameter I am trying to pass a string of comma-separated values 我正在尝试传递一串用逗号分隔的值

Thanks 谢谢

The only way you can pass dynamic number of values in the SQL query TESTID IN (...) part is to use a subselect. 您可以在SQL查询TESTID IN (...)部分中传递动态数量的值的唯一方法是使用子选择。 That applies to SQL query itself, so there is no parameter type that will solve your issue. 这适用于SQL查询本身,因此没有参数类型可以解决您的问题。

Your alternative is to build the query dynamically by using string concatenation and careful verification of each argument. 您的替代方法是使用字符串连接并仔细验证每个参数来动态构建查询。

Since you are working with IDs they are probably integers. 由于您使用的是ID,因此它们可能是整数。

List<int> testId = ...;
var sb = new StringBuilder();
sb.Append("DELETE FROM TEST WHERE TESTID IN (");
bool first = true;
foreach (var i in testId)
{
    if (first)
        first = false;
    else
        sb.Append(",");
    sb.Append(i.ToString(CultureInfo.InvariantCulture));
}
sb.Append(")");
Context.Database.ExecuteSqlCommand(sb.ToString());

Since there are no string arguments that are being appended to the query you are safe from any SQL injections - there is no way an integer will contain malicious SQL code. 由于没有附加到查询中的字符串参数,因此可以避免任何SQL注入-整数将无法包含恶意SQL代码。

The usual approach when the number of IDs is very large (so that the query will fail during compilation for being too long) is to create a temp table and insert the IDs in it. 当ID的数量很大(以至于查询在编译过程中由于时间太长而失败)时,通常的方法是创建一个临时表并在其中插入ID。

Another alternative is to pass in the values formatted as XML and in the SQL query write a subselect that retrieves them from the XML string. 另一种选择是传递格式为XML的值,然后在SQL查询中编写一个子选择,该子选择将从XML字符串中检索它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM