Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework doesn't provide DeleteAsync or AddAsync. Why?

I just noticed that EF (using version 5 here) doesn't provide DeleteAsync()/AddAsync(). I also noticed that projects like this one:

https://github.com/zzzprojects/EntityFramework-Plus

do provide DeleteAsync() as an afterthought. Why doesn't EF provide DeleteAsync() out of the box? Just curious.

Addendum: As pointed out by the maintainer of EF-Plus the 'DeleteAsync' flavor I mentioned is somewhat different than 'Delete'/'DeleteAsync' of EF in the sense that the former operates on a query targeting elements that will be matched on the db/db-server, while EF's Delete operates on elements that have already been retrieved before 'Delete()' is invoked. Despite this difference in the signature of these methods the original concern raised by my question maintains its merit.

like image 545
XDS Avatar asked Dec 14 '22 00:12

XDS


2 Answers

After watching the very enlightening material provided by MattJohnson and after probing into the implementation of Delete using reflection I surmised that the reason behind DeleteAsync() not being provided, is that delete causes the database to be changed within a single unit-of-work-instance-lifecycle.

IF someone provided a 'DeleteAsync()' operation through Task.Run() (aka without a true async implementation) this would effectively be inducing illusions through anti-patterns in the sense that developers would use this sort of API thinking they enjoy the benefits of 'true-async' but in reality they would not - they would only just suffer from unnecessary overhead ala 'await Task.Run(() => context.Foo.Delete(x))' without enjoying any benefits whatsoever.

TL;DR: The bottom-line explanation on why the folks of EF dont offer 'DeleteAsync()'/'AddAsync()' is that 'async methods shouldn't lie' (as MattJohnson pointed out) and 'DeleteAsync()'/'AddAsync()' would be bound to lie given the current implementations of EF at the time of this writing.

like image 125
XDS Avatar answered Dec 17 '22 00:12

XDS


Disclaimer: I'm the owner of Entity Framework Plus

There is a huge difference between Add && Remove from Entity Framework and Delete from my library.

Add/Remove

The Add method will only add the entity to the ChangeTracker while the Remove method will only change the EntityState to "Deleted" in the ChangeTracker.

As @Ivan specified, the Remove doesn't save changes directly in the database until you call SaveChanges or SaveChangesAsync

Delete

This feature deletes rows from a database without loading entities in the context.

Calling this method may take quite some time depending on the number of rows that will be deleted in the database.

So, offering a DeleteAsync method can make sense here.

As @Matt specified, the library currently uses Task.Run instead of truly being async which will be eventually fixed.

like image 31
Jonathan Magnan Avatar answered Dec 17 '22 01:12

Jonathan Magnan