我正在使用带有Dapper-Extensions的Dapper。我正在逐个删除所有对象:
dbConnection.Delete<MyObj>(data);这不仅对性能不好,而且因为如果删除失败,我希望回滚整个操作。有没有办法执行“大规模”删除,例如传递一个对象列表而不是data
发布于 2018-10-01 19:21:49
您可以通过IPredicate根据条件(WHERE子句)一次删除多条记录。
如果您只传递空的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));交易是另一回事。您可以将所有当前代码放入事务中。您也可以将我的代码放入事务中。在我的代码中,transaction并没有太大的不同;尽管建议始终使用transaction。
关于传递对象列表,我看不到任何方法。以下是Dapper扩展的两种删除记录的扩展方法:
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;它们都不接受对象列表。一个接受谓词,另一个接受单个宾语。
https://stackoverflow.com/questions/52588892
复制相似问题