1

我将 Dapper 与 Dapper-Extensions 一起使用。我目前正在一个一个地删除所有对象:

dbConnection.Delete<MyObj>(data);

这不仅对性能不利,而且因为如果删除失败,我想回滚整个操作。有没有办法执行“大规模”删除,例如传递对象列表而不是data

4

1 回答 1

1

您可以一次性IPredicate根据条件(WHERE 子句)删除多条记录。

如果您只是传递 empty IPredicate,则表中的所有记录都将被删除。

以下函数处理这两种情况:

protected void DeleteBy(IPredicate where)
{//If 'where' is null, this method will delete all rows from the table.
    if(where == null)
        where = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };//Send empty predicateGroup to delete all records.

    var result = connection.Delete<TPoco>(predicate, ......);
}

在上面的代码中,TPoco是映射到您正在谈论的数据库表的 POCO 类型。

您可以构建谓词,如下所示:

var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
if(!string.IsNullOrEmpty(filterValue))
    predicateGroup.Predicates.Add(Predicates.Field<MyPoco>(x => x.MyProperty, Operator.Eq, PredicateGroup));

交易是另一回事。您可以将所有当前代码放入事务中。您也可以将我的代码放入事务中。使用我的代码,事务并没有太大区别;尽管建议始终使用事务。

关于传递对象列表,我看不到任何方法。以下是 Dapper Extensions 的两种删除记录的扩展方法:

public static bool Delete<T>(this IDbConnection connection, object predicate, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : class;
public static bool Delete<T>(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : class;

它都不接受对象列表。一个接受谓词,另一个接受单个对象。

于 2018-10-01T11:21:48.920 回答