0

I have a Repository project like this.

https://github.com/tugberkugurlu/GenericRepository/tree/master/src

I have a method.

public void Edit(TEntity entity)
{
   _dbContext.SetAsModified(entity);
}


public void SetAsAdded<TEntity>(TEntity entity) where TEntity : class
{
   DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
   dbEntityEntry.State = EntityState.Added;
}

But I am getting while update record. I am getting sometimes this error.

Attaching an entity of type 'TP.Model' 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.

5
  • Have you seen this? stackoverflow.com/questions/23201907/… Commented Nov 6, 2017 at 8:28
  • I read over and over, but I don't understand there is a problem. Commented Nov 6, 2017 at 8:31
  • Debug your context dbset Local collection... if it already contains an entity with your id, then your code might fail. However, you didn't show enough of your code, so we can,t be sure what the problem is. Commented Nov 6, 2017 at 8:42
  • I have added full code with link @grek40 Commented Nov 6, 2017 at 8:46
  • No, you need to add how you use the code, not just how the repository is designed. Because the way the repository is resigned means, that you will get this error if you use it in the wrong way. Commented Nov 6, 2017 at 9:13

1 Answer 1

0

I solved the problem like this. I checked the first columns. Afterwards, I did something like this.

_dbSet = dbContext.DbSet<TEntity>();

The rest is cake.

_dbSet.Attach(entity);
                DbEntityEntry entry = _dbContext.Entry(entity);
                foreach (var proprty in entry.OriginalValues.PropertyNames)
                {
                    var Current = entry.CurrentValues.GetValue<object>(proprty);
                    var New = entry.GetDatabaseValues().GetValue<object>(proprty);

                    if (Current != null)
                    {
                        if (!object.Equals(New, Current))
                        {
                            entry.Property(proprty).IsModified = true;
                        }
                    }
                }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.