2

Plain and simple, is there any difference between

DbSet().Remove(x)

to

context.Entry(x).State = State.Deleted?

Thanks

  • Look at [this](http://stackoverflow.com/questions/17723626/entity-framework-remove-vs-deleteobject). – BWA Feb 15 '16 at 22:38

1 Answers1

2

Not that I can tell, the MSDN article for Remove says

Marks the given entity as Deleted such that it will be deleted from the database when SaveChanges is called. Note that the entity must exist in the context in some other state before this method is called.

.Remove is likely just the preferred way to remove items.

EDIT:

Also, the MSDN article for the EntityState says this for deleted.

The entity is being tracked by the context and exists in the database, but has been marked for deletion from the database the next time SaveChanges is called.

Which just further solidifies that they are effectively the same thing.

Justin Packwood
  • 337
  • 2
  • 12
  • And in order to remove an Item it must be loaded to cach right? There is no such thing to remove even when knowing the key, is it correct? –  Feb 16 '16 at 05:54
  • Yes they both expect the entity to exist, however the second method, if used with a linq expression could be used to attempt to set an entity by I'd as deleted (even if it didn't exist, as the linq would just come back with nothing) – Justin Packwood Feb 16 '16 at 11:43
  • One difference is if you set `EntityState.Deleted` on an entity that is `EntityState.Added`, it will get an exception when you try to save changes because the record it tries to delete already does not exist. But `Remove` will change it to `Detached`. It also sounds like `Remove` makes some attempts at handling foreign keys on included entities? https://forums.asp.net/t/2015170.aspx?Using+dbset+Add+adset+Remove+Versus+using+EntityState+Added+EntityState+deleted – xr280xr Feb 09 '21 at 06:22