Search code examples
entity-frameworkentity-framework-6.1

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


Solution

  • 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.