codes:
public void test2()
{
var ids = new int[] { 39, 40, 41 };
var founds = _db.DB_MODEL.AsNoTracking().Where(x => ids.Contains(x.ID)).ToArray();
founds.Repeat(x =>
{
x.IsDefault = false;
_db.Set<QuoteEntity>().Add(x);
_db.Entry(x).State = System.Data.Entity.EntityState.Modified;
});
var target = _db.DB_MODEL.AsNoTracking().FirstOrDefault(x => x.ID == 41);
target.IsDefault = true;
_db.Set<QuoteEntity>().Add(target);
_db.Entry(target).State = System.Data.Entity.EntityState.Modified;
_db.SaveChanges();
}
then I got below errors:
System.InvalidOperationException: 'Attaching an entity of type 'ENTITY NAME' failed because another entity of the same type already has the same primary key value.
This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values.
This may be because some entities are new and have not yet received database-generated key values.
In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'
If I remove AsNoTracking(), then it works.
But I really need to AsNoTracking to avoid changing entity inadvertently.