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.

Caner
  • 813
  • 1
  • 12
  • 26
  • Have you seen this? https://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent – Mohammed Gadi Nov 06 '17 at 08:28
  • I read over and over, but I don't understand there is a problem. – Caner Nov 06 '17 at 08: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. – grek40 Nov 06 '17 at 08:42
  • I have added full code with link @grek40 – Caner Nov 06 '17 at 08: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. – grek40 Nov 06 '17 at 09:13

1 Answers1

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;
                        }
                    }
                }
Caner
  • 813
  • 1
  • 12
  • 26