entity framework Remove vs EntityState.Deleted
Asked Answered
P

1

11

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

Prussia answered 7/3, 2015 at 8:13 Comment(2)
I have found now a very interesting post: forums.asp.net/t/…Prussia
Also be aware of impact on cascaded delete when related tables exist.Hype
T
18

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.

Tabular answered 7/3, 2015 at 10:9 Comment(2)
Hi, I can't find the method Delete, Should I create it?Tyrannosaur
The method should be part of EntityFramework.Extended. Maybe you missed to include the nuget package?Tabular

© 2022 - 2024 — McMap. All rights reserved.