【问题标题】:Delete all but top 10 for every type Entity Framework删除每种类型实体框架的前 10 名以外的所有内容
【发布时间】:2016-01-27 22:50:18
【问题描述】:

假设我有一张这样的桌子:

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 时如何做到这一点?

【问题讨论】:

    标签: c# sql .net entity-framework


    【解决方案1】:
    // 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);
    

    【讨论】:

      【解决方案2】:

      如果你有很多数据,我猜这需要一段时间。

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

      会成功的 (写在记事本里)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-30
        • 1970-01-01
        • 2013-08-05
        • 1970-01-01
        • 1970-01-01
        • 2013-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多