linq to sql batch delete

后端 未结 4 1172
一生所求
一生所求 2021-01-13 01:06

I have the following DB: Posts which have an Id, Tags also with Id, and TagsToPosts table which have T

4条回答
  •  自闭症患者
    2021-01-13 01:50

    My solution which lets you make deletions determined by a class field:

    public static void DeleteByPropertyList(List listToDelete, Expression> getField, DataContext context) where T : class {
        List> partitionedDeletes = listToDelete.Select(d => string.Format("'{0}'", getField.Compile()(d).ToString())).ToList().Partition(2000).ToList();
        Func>, string> GetFieldName = propertyLambda => ((MemberExpression)propertyLambda.Body).Member.Name;
        MetaTable metaTable = context.Mapping.GetTable(typeof(T));
        string tableName = string.Format("{0}.{1}", metaTable.Model.DatabaseName, metaTable.TableName);
        foreach (List partitionDelete in partitionedDeletes) {
            string statement = "delete from {0} where {1} in ({2})";
            statement = string.Format(statement, tableName, GetFieldName(getField), string.Join(",", partitionDelete));
            context.ExecuteCommand(statement);
        }
    }
    
    public static IEnumerable> Partition(this IList source, int size) {
        for (int i = 0; i < Math.Ceiling(source.Count / (double)size); i++)
        yield return new List(source.Skip(size * i).Take(size));
    }
    

    Usage:

        List deletions = new List();
        // populate deletions
        LinqToSqlHelper.DeleteByPropertyList(deletions, oi => oi.OrderItemId, context);
    

    It only works with a single field, but it could be extended to composite fields easily enough.

提交回复
热议问题