假设我有一张表:
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
时如何完成?
答案 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);
会做的伎俩 (写在记事本中)