1

I have run into a scenario where I need to bulk delete on a specific date time. It seems that the EF+ batch delete function doesn't correctly equate date time and perform the action.

It does work fine on other field types, but just not DateTime. Is there some special formatting I should be doing to perform this action properly?

The backend SQL Server table has the FileCreatedDate as DateTime2(7). And records all contain the DateTime.UtcNow date/time that is specified in the code, since an initial pass prior to this code created those records. This is a fallback to clean out the records that got created if an error occurred.

I have the following code:

var fileCreatedDate = DateTime.UtcNow;

using (var db = new MyContextDb())
{
    db.SampleModel.Where(e => e.FileCreatedDate == fileCreatedDate).Delete();
}

This code doesn't work. It doesn't delete the records whose time matches the criteria.

Any ideas what might be the problem?

Dale K
  • 25,246
  • 15
  • 42
  • 71
user1161137
  • 1,067
  • 1
  • 11
  • 31
  • 1
    Perhaps you are running into [this EF issue with datetime values](https://social.msdn.microsoft.com/Forums/silverlight/en-US/de5dbf3e-8c95-40f4-9e31-b71f1f31983d/change-in-datetime2-implementation-in-sql-server-2016?forum=transactsql) where EF does a cast to datetime2 for comparing to a datetime column column. – SMor Aug 05 '20 at 23:25

1 Answers1

0

Can you try to remove the entities using range?

like so:

db.SampleModel.RemoveRange(db.SampleModel.Where(e => e.FileCreatedDate == fileCreatedDate));
db.SaveChanges();
L0uis
  • 703
  • 5
  • 8