.net 使用Dapper删除列表< T>

7gs2gvoe  于 2022-12-01  发布在  .NET
关注(0)|答案(5)|浏览(282)

使用Dapper或Dapper.SimpleCRUD,如何从表中删除List。类似于:

public static void DeleteList<T>(List<T> listToDelete)
    {
        using (var connection = OpenConnection())
        {
            connection.Delete<T>(listToDelete);
        }
    }

但当我试着那样做的时候我就...
DataModel.MyTable类型的成员不能用作参数值
是传入WHERE子句的唯一选项吗?

0x6upsns

0x6upsns1#

衣冠楚楚的人不知道你的实体;它不像实体框架。2你需要自己执行一个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});
        }
    }
}

或多次执行命令

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());
    }
}
k4aesqcs

k4aesqcs2#

轻松的道:

public void BulkDelete(IEnumerable<int> idList)
    {
        using (var connection = GetNewConnection())
        {
            connection.Execute("Delete FROM MY_TABLE WHERE Id in @idList", new { idList });
        }
    }
jogvjijk

jogvjijk3#

我没有看到任何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});
bqujaahr

bqujaahr4#

不知道为什么选择上面的答案。但是Dapper开箱即用不支持列表功能。而不是在我的答案中重新创建轮子,请参见:Delete rows from mysql server from a list of ID's C# ...只是我的2c。

vbkedwbf

vbkedwbf5#

当使用Dapper.Contrib.Extensions包时,只要你试图通过Primary Key删除(由User对象上的[Key]注解指示),就可以使用db.Delete(user);。一旦你想通过其他任何东西删除,最好使用db.Execute(query, params);
Dapper.Contrib.Extension Delete documentation

相关问题