代码之家  ›  专栏  ›  技术社区  ›  ufo

使用单个查询(或在事务中)删除多个对象

  •  1
  • ufo  · 技术社区  · 6 年前

    我正在使用Dapper和Dapper扩展。我正在逐个删除所有对象:

    dbConnection.Delete<MyObj>(data);
    

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Amit Joshi    6 年前

    你可以通过 IPredicate 一次删除基于条件(WHERE子句)的多条记录。

    如果你只是空手而过 信用证 ,将删除表中的所有记录。

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

    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扩展的两种扩展方法:

    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;
    

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