-1

I am facing an issue with dbcontext entries.

I have 2 Entities to save to database with EF Core. EntityA EntityB

EntityA , is already saved to database but EntityB not.

When I call my code to SaveChanges EntityA, I have an error Duplicate entry '7c4e4552-c46f-4153-b1e8-c9ebfca135a4' for key 'PRIMARY', normal, then I want to save EntityB , but when a I call my SaveChanges, I see that I have 2 entries in my collection of entries of DBContext and I can´t save EntityB because, EF try again to save EntityA.

public async Task<TEntity> AddAsync(TEntity entity)
{
    if (entity == null)
    {
        throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
    }

    try
    {
        await Context.AddAsync(entity);
        await Context.SaveChangesAsync();
        return entity;
    }

    catch (Exception ex)
    {
        throw new Exception($"{nameof(entity)} could not be saved. {errorMessage}");
    }
}


public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get all the entities that inherit from AuditableEntity
            // and have a state of Added or Modified
            var entries = ChangeTracker
                .Entries()
                .Where(e => e.Entity is AuditableEntity && (
                        e.State == EntityState.Added
                        || e.State == EntityState.Modified));

            // For each entity we will set the Audit properties
            foreach (var entityEntry in entries) ***//Here are 2 when I only want 1***
            {
                // If the entity state is Added let's set
                // the CreatedAt and CreatedBy properties
                if (entityEntry.State == EntityState.Added)
                {
                    ((AuditableEntity)entityEntry.Entity).CreatedAt = DateTime.UtcNow;
                    ((AuditableEntity)entityEntry.Entity).CreatedBy = _httpContextAccessor?.HttpContext?.User?.Identity?.Name ?? MyApp;
                }
                else
                {
                    // If the state is Modified then we don't want
                    // to modify the CreatedAt and CreatedBy properties
                    // so we set their state as IsModified to false
                    Entry((AuditableEntity)entityEntry.Entity).Property(p => p.CreatedAt).IsModified = false;
                    Entry((AuditableEntity)entityEntry.Entity).Property(p => p.CreatedBy).IsModified = false;
                }

                // In any case we always want to set the properties
                // ModifiedAt and ModifiedBy
                ((AuditableEntity)entityEntry.Entity).ModifiedAt = DateTime.UtcNow;
                ((AuditableEntity)entityEntry.Entity).ModifiedBy = _httpContextAccessor?.HttpContext?.User?.Identity?.Name ?? MyApp;
            }

            // After we set all the needed properties
            // we call the base implementation of SaveChangesAsync
            // to actually save our entities in the database
            return await base.SaveChangesAsync(cancellationToken);
        }
jolynice
  • 514
  • 1
  • 8
  • 25

1 Answers1

0

Did you enable the code migrations in your project?

If not , you see this error because EF is trying to create EntityA again as you have not enabled the code migrations.Code Migration will incrementally update the data to keep it in sync with the application's data model while preserving existing data in the database. Refer to the link below to add migrations.Tutorial MSDN

Lenka
  • 1
  • 3
  • Thanks Lenka, I will recheck my migration. I will give feedback. – jolynice Aug 04 '20 at 19:10
  • Continues with the same issue. I will check before to add to database if the entity already exist, then I will managed it. If exist I send it to update if not I save it. – jolynice Aug 04 '20 at 19:16
  • you mentioned about duplicate entry error for primary key, this happens if you have duplicate values in your save data. – Lenka Aug 05 '20 at 00:39