I am wondering about why BulkDelete not throwing an exception if there is no such entity to delete on database? I am forced to check database if there are some matching entities and after calling BulkDelete method sending matched entities which I've got from querying database. Do EF Extensions has some options to automate it?
Why EF Extensions not throwing an exception when there is any such entity on table to delete?
200 views Asked by Shahin Jabbarov AtThere are 3 answers
On
The BulkDelete has been optimized for performance.
So indeed, there is no check about if the entity exists or not first, we just perform the Delete operation.
Something you could do on your side to make it easier is using the BulkRead method before using the BulkDelete.
var customers = context.Customers.BulkRead(deserializedCustomers);
Docs: https://entityframework-extensions.net/bulk-read
By using this method, you will be able to easily compare with your current list to get the list of customer doesn't exist in the database for example.
You could also get the RowAffecteds and compare it with your list count: https://entityframework-extensions.net/rows-affected
On
I am wondering about why BulkDelete not throwing an exception if there is no such entity to delete on database?
Because there is nothing wrong with having a filter that ends up yielding 0 results. That is not inherently an erroneous state.
Sure, for a specific use case you may have been expecting to find at least something, but a generalized library cannot account for your specific expectation in your specific use case. There are plenty of cases where ending up not deleting something is not a problematic scenario, e.g. a daily cleanup job that removes old entries if there are any. If there are no old entries, that's not a reason to throw an exception. It just means that nothing needed to be deleted.
This is no different from why a foreach doesn't throw an exception when you pass it an empty collection. The foreach is still doing its job, i.e. performing the work for each item in the collection. There are 0 items, and therefore it performs the work 0 times.
You dont have to check database. I am assuming you are using
EF Extensions - BulkDelete. When you call BulkDelete, you just delete it but to make changes to the database, you have to.SaveChanges();- This method however return the number of rows affected.So, if the number is 0, then you know your
DELETEfailed. If the number is above 0, then you know theDELETEwas successfull