Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework Remove vs EntityState.Deleted

What is the diff between these two statements?

Both should delete an entity.

 _context.Entry(new Schoolyear { Id = schoolyearId }).State = EntityState.Deleted;
 _context.Schoolyears.Remove(new Schoolyear { Id = schoolyearId });

and for those who does not know the EF Extensions:

 _context.Schoolyears.Delete(s => s.Id == schoolyearId);

Thats even cooler :D

like image 473
Elisabeth Avatar asked Mar 07 '15 08:03

Elisabeth


People also ask

Which method is used to let the DbContext know an entity should be deleted?

DbContext. Remove Method (Microsoft.

What is EntityState?

EF API maintains the state of each entity during its lifetime. Each entity has a state based on the operation performed on it via the context class. The entity state represented by an enum System.

What is EntityState modified?

EntityState.Added : EntityState.Modified; context.SaveChanges(); } } Note that when you change the state to Modified all the properties of the entity will be marked as modified and all the property values will be sent to the database when SaveChanges is called.


1 Answers

They are the same but both will fail. EF internally uses an ObjectManager to keep track of all elements used by EF. Entries to the ObjectManager are added by using retrieval functions of EF or by adding new entries to the EF with using _context.Schoolyears.Add(obj).

Referencing entries not stored in the object manager will usually create InvalidOperationException exceptions. The behavior of the following is similar:

Schoolyear year = context.Schoolyears.Single(x => x.Name == "2013");
_context.Schoolyears.Remove(year);
_context.SaveChanges();

or

Schoolyear year = context.Schoolyears.Single(x => x.Name == "2013");
_context.Entry(year).State = EntityState.Deleted;
_context.SaveChanges();

but EF does some more checks and status change activities in the first approach.

I would always prefer the first approach if possible.

On the other side of the game there's EntityFramework.Extended. This library allows mass updates/deletes on EF contexts.

This library does not use the ObjectManager, therefore you are allowed to use

 _context.Schoolyears.Delete(s => s.Id == schoolyearId);

Hint: You can also use (preferred)

 _context.Schoolyears.Where(s => s.Id == schoolyearId).Delete();

Warning: Please ensure that you do not manipulate objects at the same time in EF and EF.Extended. This Could cause unpredictable results or exceptions.

like image 63
Stephen Reindl Avatar answered Oct 11 '22 01:10

Stephen Reindl