Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a List<T> using Dapper

Tags:

c#

.net

dapper

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?

like image 715
Casey Crookston Avatar asked Dec 06 '22 13:12

Casey Crookston


1 Answers

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());
    }
}
like image 58
Win Avatar answered Jan 04 '23 05:01

Win