Using Dapper or Dapper.SimpleCRUD, How might I delete a List from a table. Something like:
public static void DeleteList<T>(List<T> listToDelete)
{
using (var connection = OpenConnection())
{
connection.Delete<T>(listToDelete);
}
}
But when I try that, I get...
The member of type DataModel.MyTable cannot be used as a parameter value
Is the only option to pass in a WHERE clause?
I don't see any Dapper method for what you want to achieve. The only options are two single deletes and two multiple deletes.
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)
Both multiple deletes require you to pass conditions or a where clause. Examples:
connection.DeleteList<User>(new { Age = 10 });
connection.DeleteList<User>("Where age > 20");
connection.DeleteList<User>("Where age > @Age", new {Age = 20});
Dapper doesn't know your entity; it is not like Entity Framework. You need to execute a SQL Command or a Store Procedure by yourself.
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});
}
}
}
Or 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());
}
}