简体   繁体   English

如何使用Entity Framework按创建日期升序删除1000条记录?

[英]How to delete 1000 records based upon created date ascending using Entity Framework?

I have a requirement to delete last 1000 records from a table based upon created date and then insert new 1000 records from a different table. 我需要根据创建日期从表中删除最后1000条记录,然后从其他表中插入新的1000条记录。

What would be the best possible way to do it? 最好的方法是什么?

public void mymethod()
{
     // TestBasketRequests (delete thousands records from here)
     // Call Delete();
}

public void Delete(IList<TestBasketRequest> TestBasketRequests)
{
    using (var dbContext = new myContext())
    {
        dbContext.Entry(TestBasketRequests).State = EntityState.Deleted;
        dbContext.SaveChanges();
    }
}

The

RemoveRange()

method is used to delete multiple items from the database. 方法用于从数据库中删除多个项目。 And in the method you have to use to get the last 1000 items using 在方法中,您必须使用来获取最近的1000个项目

TakeLast() 

will only return last items based on the order they were added to the database. 将仅根据最后一项添加到数据库中的顺序返回最后一项。

Inside your mymethod() u have to write something like this 在您的mymethod()内部,您必须编写如下内容

var lastN = MyDbContext.MyDbSet
                   .OrderByDescending(g => g.CreateDate)
                   .Take(1000);

MyDbContext.MyDbSet.RemoveRange(lastN);

I didnt test this code.you can make changes as per your requirements. 我没有测试此代码。您可以根据需要进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在较短的时间内使用实体框架同时编辑1000条记录 - How to edit 1000 records at time using entity framework in less time 如何使用 ExecuteSqlCommand 删除实体框架中的记录? - How can I delete records in Entity Framework using ExecuteSqlCommand? 如何使用实体框架过滤字符串日期列上的记录 - How to filter records on a string date column using entity framework 如何删除 Entity Framework Core 中指定日期之前的记录,不包括最新的? - How do I delete records before a specified date in Entity Framework Core excluding the latest? 如何在不使用 SQL 的情况下使用实体框架有效地删除表中的所有记录? - How can I efficiently delete all records in a table using Entity Framework without using SQL? 实体框架:如何在更新或删除“通用”父对象时删除相关实体 - Entity Framework: how to delete related entity upon update or delete of 'generic' parent 如何在实体框架中循环创建和删除记录 - How do I create and delete records in Entity Framework in a loop 如何删除 Entity Framework.Core 中的一组记录? - How do I delete a set of records in Entity Framework .Core? 如何使用Entity Framework删除相关字段 - How to delete related fields using Entity Framework 如何在实体框架中删除 - How to delete in Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM