为每种类型的Entity Framework删除除前10名之外的所有内容

时间:2016-01-27 22:50:18

标签: c# sql .net entity-framework

假设我有一张表:

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

现在,我想删除所有行,只留下所有类别中的前10行(前10位,我的意思是根据createdDate最新的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

在Entity Framework中使用DbContext时如何完成?

2 个答案:

答案 0 :(得分:3)

// 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);

答案 1 :(得分:0)

如果您有大量数据,那么猜测它会花费一些时间。

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

会做的伎俩 (写在记事本中)