[英]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.