Entity Framework entity state

Time:2022-11-25

Starting today, we begin to explain the entity state and data operations in EF. This article first explains the entity state.
Through the previous study, we know that EF is responsible for tracking the state of the entity through the upper and lower bits. The location of the entity state is in the namespaceSystem.Dat.EntityinnerEntityState, there are five specific states as follows:

  1. Detached
  2. Unchanged
  3. Added
  4. Deleted
  5. Modified

Let’s explain the difference

Zero, Detached

Sometimes we only need entity display, but not entity update. In order to improve performance, we don’t need EF context to track entities. We use it at this timeDetachedstate. We only need to use when queryingAsNoTracking()The object of the afterlife query isDetachedstate. The example code is as follows:

var person = db.Person.AsNoTracking().Where(p=>p.Id==1).FirstOrDefault();

Note: becauseAsNoTrackingis a method of the DbQuery class, so first callAsNoTrackingmethod.

1. Unchanged

In this state the entity is tracked by the context, but the value in the database has not changed. If the entity does not exist in the database, but the entity is to be tracked by the context, and the entity value has not changed, this time you can passAttachDo additional tracking and then mark the entity state asUnchanged. The example code is as follows:

using (var db = new EFDbContext())
{
  var user =new User()
  {
    Name = "Zhang San",
    Age = 12
  }
  db.User.Attach(user);
  db.Entry(user).State = EntityState.Unchanged;
  db.SaveChanges();
}

Two, Added

It will be used when adding new operationsAddedstate. Mark asAddedstate, indicating that the corpse context is tracked but does not exist in the database, when we callSaveChangesmethod data will be saved into the database. If you want to mark an entity state as that, you can use two methods:

  1. Indirect marking, throughAddMethod call, the sample code is as follows:
using (var db = new EFDbContext())
{
  var user = new User()
  {
    Name = "Zhang San"
    Age = 12
  }
  db.User.Add(user);
  db.SaveChanges();
}
  1. Explicitly marked, by callingEntrymethod, the sample code is as follows:
using (var db = new EFDbContext())
{
  var user = new User()
  {
    Name = "Zhang San"
    Age = 12
  }
  db.Entry(user).State = EntityState.Added;
  db.SaveChanges();
}

3. Deleted

If you need to delete an entity from the database, you can useDeletedstate, when callingSaveChangesmethod the data will be deleted from the database. andAddedLike state, there are two ways to delete an entity:

  1. by callingRemoveorRemoveRangemethod, the sample code is as follows:
using (var db = new EFDbContext())
{
  var user = db.User..Where(p => p.Id == 1).FirstOrDefault();
  db.User.Remove(user);
  db.SaveChanges();
}

Note:Removefor deleting a single entity,RemoveRangeUsed to delete multiple entities.

  1. Explicitly marked, by callingEntrymethod, the sample code is as follows:
using (var db = new EFDbContext())
{
  var user = db.User..Where(p => p.Id == 1).FirstOrDefault();
  db.Entry(user).State = EntityState.Deleted;
  db.SaveChanges();
}

4. Modified

When we modify the data, we need to useModifiedstate, when callingSaveChangesmethod will modify the data in the database. There is only one way to modify data in EF, by callingEntrymethod, the sample code is as follows:

using (var db = new EFDbContext())
{
  var user = db.User..Where(p => p.Id == 1).FirstOrDefault();
  db.Entry(user).State = EntityState.Modified;
  db.SaveChanges();
}

5. Special Tips

Almost all states can pass betweenEntry(T).StateMandatory state transition is performed in the same way, because state changes are all dependent on Id (except Added). Let’s take a look at the mutual conversion of the above five states through the following figure:
Entity Framework entity state