删除每种类型实体框架的除前 10 个之外的所有内容

本文关键字:种类 类型 实体 框架 删除 | 更新日期: 2023-09-27 18:32:08

假设我有一个表格,如下所示:

Id    Name   Category   CreatedDate
1     test   test       10-10-2015
2     test1  test1      10-10-2015
...

现在,我想删除所有行,只保留所有类别中的前 10 名(根据 createdDate,前 10 名是指最新的 10 名)。

使用原始 SQL,它会像:

DELETE FROM [Product]
WHERE id NOT IN
(
    SELECT id FROM
    (
        SELECT id, RANK() OVER(PARTITION BY Category ORDER BY createdDate DESC) num
        FROM [Product]
    ) X
WHERE num <= 10

在实体框架中使用DbContext时如何完成此操作?

删除每种类型实体框架的除前 10 个之外的所有内容

// GET all products
var list = ctx.Products.ToList();
// GROUP by category, ORDER by date descending, SKIP 10 rows by category
var groupByListToRemove = list.GroupBy(x => x.Category)
                              .Select(x => x.OrderByDescending(y => y.CreatedDate)
                                            .Skip(10).ToList());
// SELECT all data to remove
var listToRemove = groupByListToRemove.SelectMany(x => x);
// Have fun!
ctx.Products.RemoveRange(listToRemove);

如果你有很多数据,猜测它需要一丝一辙,但是。

var oldItems = efContext.Products
.GroupBy(x => x.Category, 
(c,p) => p.OrderByDescending(x => p.createdDate).Skip(10))
.SelectMany(p => p);
efContext.Products.RemoveRange(oldItems);

会做这个伎俩(写在记事本上)