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
DbContext. Remove Method (Microsoft.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With