entity framework Remove vs EntityState.Deleted

entity-framework entity-framework-6.1

Question

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

1
6
3/7/2015 8:31:50 AM

Accepted Answer

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.

12
3/7/2015 10:09:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow