使用Dapper或Dapper.SimpleCRUD,如何从表中删除列表。类似的东西:
public static void DeleteList<T>(List<T> listToDelete)
{
using (var connection = OpenConnection())
{
connection.Delete<T>(listToDelete);
}
}
但是当我尝试的时候,我得到......
DataModel.MyTable类型的成员不能用作参数值
传递WHERE子句的唯一选择是什么?
答案 0 :(得分:4)
Dapper并不了解你的实体;它不像实体框架。您需要自己执行SQL命令或存储过程。
public static void DeleteList(List<int> idToDelete)
{
using (IDbConnection conn = new SqlConnection(connString))
{
conn.Open();
foreach (int id in idToDelete)
{
conn.Execute(@"DELETE FROM [User] WHERE Id = @Id", new {Id = id});
}
}
}
或Execute a Command multiple times
public static void DeleteList(List<int> idToDelete)
{
using (IDbConnection conn = new SqlConnection(connString))
{
conn.Open();
conn.Execute(@"DELETE FROM [User] WHERE Id = @Id",
idToDelete.Select(x => new { Id = x }).ToArray());
}
}
答案 1 :(得分:3)
简便方法:
public void BulkDelete(IEnumerable<int> idList)
{
using (var connection = GetNewConnection())
{
connection.Execute("Delete FROM MY_TABLE WHERE Id in @idList", new { idList });
}
}
答案 2 :(得分:2)
我没有看到任何你想要实现的Dapper方法。唯一的选择是两个单个删除和两个多个删除。
public static int Delete<T>(this IDbConnection connection, int Id)
public static int Delete<T>(this IDbConnection connection, T entityToDelete)
public static int DeleteList<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
public static int DeleteList<T>(this IDbConnection connection, string conditions, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
多次删除都要求您传递条件或where子句。例子:
connection.DeleteList<User>(new { Age = 10 });
connection.DeleteList<User>("Where age > 20");
connection.DeleteList<User>("Where age > @Age", new {Age = 20});
答案 3 :(得分:0)
不确定选择上述答案的原因。但开箱即用的Dapper不支持列表功能。而不是在我的答案中重新创建轮子,请参阅:Delete rows from mysql server from a list of ID's C# ...只是我的2c。