none
Entity Framework and LINQ to Entities - Update failure RRS feed

  • Question

  • Our Team is working on Entity Framework, Repository pattern and LINQ to update Entities. 

    We are facing major issue on Update method.  When we try to update tables we are getting error as below.

    Attaching an entity of type 'Common.DAL.TableName' 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.

    Behavior is update work on my machine but not on test environment. Sometime it happen that code works on my machine but not my colleagues machine. it is very inconsistent. We cannot draw pattern for it.

    Previous update method code in Repository.cs was.

      public void Update(TEntity entity)

        {       

    _entities.Attach(entity);

            _context.Entry(entity).State = EntityState.Modified;

            _context.SaveChanges();       

        }

    Then code changed to 

      public void Update(TEntity entity)

        {       

    entities.Attach(entity);

            _context.Entry(entity).State = EntityState.Modified;

            _context.SaveChanges();

            _context.Entry(entity).State = EntityState.Detached;

            _context.SaveChanges();     

        }

    and finally code changed to 

        public void Update(TEntity entity)

        {

            _context.Entry(entity).State = EntityState.Detached;

            _context.SaveChanges();

            _context.Entry(entity).State = EntityState.Modified;

            _context.SaveChanges();

           

        }

    which is working but we are afraid that issue may reappear again.

    About EDMX file some tables are with key constrain but some are independent. 

    Monday, October 16, 2017 11:49 AM

All replies

  • @Lax Luther,

    As this is a EF related case we will move your case to the right forum.

    Best regards,

    Barry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, October 17, 2017 1:41 AM
  • Thanks You for your support.
    Tuesday, October 17, 2017 5:44 AM
  • My EF code is some similar to yours. The difference is that I did not set state to modified.

    The code works fine online more than 1 year.

    EF caches the entity when attaching entity. Then saving the changes, EF can detect which property is changed and update the entity automatically. So, in my opinion, when you set the entity to modified, 

    EF consides there are two ways to update the entity in the same time and is confused about the conflict.

    My Code:

    public void Update<TEntity>(TEntity entity, Action<TEntity> update) where TEntity : class { ParameterChecker.CheckNull(entity, "entity"); ParameterChecker.CheckNull(update, "update"); var db = (TDbContext)Activator.CreateInstance(typeof(TDbContext), this.connectionString); using (db) { db.Set<TEntity>().Attach(entity); // Auto attach last update time. var now = DateTime.Now; var dbUpdateTracking = entity as IDbUpdateTracking; if (dbUpdateTracking != null) { now = dbUpdateTracking.LastUpdateTime; }

    // Updates the entity by action.

    update(entity); if (dbUpdateTracking != null && dbUpdateTracking.LastUpdateTime == now) { dbUpdateTracking.LastUpdateTime = DateTime.Now; } db.SaveChanges(); } }

    Example:

    this.dbManager.Update(student, _ => 
    {
         _.Sex = "Male",
         _.Age = 18
    });

    Tuesday, October 17, 2017 12:58 PM
  • Hi,

    Here i would Clarify for Attach() method.

    If you have an entity(detached state), you already know it exists in Database but it is not tracked by Data context. This time, you can use Attach() method to tell the Data context to track this entity the entity state change to Unchanged.

    it looks like you want add or update the entity.

    Try following method:

    public void InsertOrUpdate(TEntity entity)
        {       
            _context.Entry(entity).State =entity.Id==0? EntityState.Add:EntityState.Modified;
    
            _context.SaveChanges();        
    
        }
    

    Sincerely,

    Bob


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, October 24, 2017 9:34 AM