0

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.

Community
  • 1
  • 1
ibamboo
  • 1,467
  • 13
  • 15
  • If you want EF to keep track of entity instances (so when you get the same entity again – 41 in this case) you need tracking.Please expand (in the question) on why you think you might changing objects you don't want to change? – Richard Apr 22 '18 at 06:25
  • Possible duplicate of [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](https://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent) – Saadi Apr 22 '18 at 06:26
  • 1. What is the primary key of your Table? 2. Instead of fetching through AsNoTracking and they adding it into DB does not make sense. Why don't you fetch with tracking enabled and change the require property without excitability setting State. – user1672994 Apr 22 '18 at 06:48
  • The first time you use `db.Set().Add(x);` for Id 41, I guess it works? The second time you try to Add the same entity with ID 41. Is that second time `_db.Set().Add(target);` the line that gives the error? If not, please specify. – oerkelens Apr 22 '18 at 07:08

0 Answers0