假设我有一张桌子,像:
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时,是如何做到这一点的?
发布于 2016-01-27 23:00:08
// 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);发布于 2016-01-27 22:55:14
如果你有很多数据的话。
var oldItems = efContext.Products
.GroupBy(x => x.Category,
(c,p) => p.OrderByDescending(x => p.createdDate).Skip(10))
.SelectMany(p => p);
efContext.Products.RemoveRange(oldItems);(用记事本写)
https://stackoverflow.com/questions/35049653
复制相似问题