Entity structure Delete vs EntityState.Deleted

What is the difference between these two statements?

Both must delete the object.

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

and for those who do not know the EF extension:

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

This is even cooler: D

+4
source share
1 answer

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

A reference to entries not stored in the object manager typically raises exceptions InvalidOperationException. 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();

EF .

, .

EntityFramework.Extended. / EF.

ObjectManager,

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

: ()

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

. , EF EF.Extended. .

+7

All Articles