EntityState.Added
can be set in two fully equivalent ways:
By setting the state of its entry in the context:
context.Entry(entity).State = EntityState.Added;
By adding it to a DbSet
of the context:
context.Entities.Add(entity);
When calling SaveChanges
, the entity will be inserted into the database. When it's got an identity column (an auto-set, auto-incrementing primary key), then after SaveChanges
, the primary key property of the entity will contain the newly generated value, even when this property already had a value.