How to save changes twice in one method using Entity Framework Core

entity-framework entity-framework-6 entity-framework-core

Question

I'm attempting to save modifications to the same entity collection twice using Entity Framework Core.

    public async Task Save(IEnumerable<Request> request)
    {            
        var entities = request.Select(x => new MyEntity()
        {
            FileName = x.FileName,                
            Status = Status.Downloading                
        });

        // save as downloading
        await _dbContext.MyFiles.AddRangeAsync(entities).ConfigureAwait(false);
        await _dbContext.SaveChangesAsync().ConfigureAwait(false);

        // start downloading
        await _storage.DownloadFilesAsync(request).ConfigureAwait(false);

        // save as downloaded
        foreach (var entity in entities)
        {
            entity.Status = Status.Downloaded;
        }

        // this save DOES NOT update the entities with status Downloaded
        await _dbContext.SaveChangesAsync().ConfigureAwait(false);          
    }

first call toSaveChanges() method generates entities with status in the database.Downloading .

I am then changing the entity's status toDownloaded and dialSaveChanges() again. But this time, the database for entities is not updated.

Since entities are already loaded in the database context, I didn't think I needed to reload them before the second call.SaveChanges . The property would be marked as changed only by changing it. But it doesn't function.

1. Update
I specifically set State as Modified and modified the code as seen below.

 // save as downloaded
 foreach (var entity in entities)
 {
    entity.Status = Status.Downloaded;      

    // The exception occurs at line below on 2nd loop
   _dbContext.Entry(entity).State = EntityState.Modified;
 }

I'm now experiencing an error

System.InvalidOperationException: The instance of entity type 'MyEntity' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context. at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)

The thing hasId a kind of propertyint also TheId furthermore has[Key] attribute.

public class MyEntity
{
   [System.ComponentModel.DataAnnotations.Key]
   public int Id {get;set;}
   public string FileName {get;set;}
   public string Status {get;set;}
}

2. Update
Consequently, after a bit more troubleshooting, I discovered the firstSaveChanges() As predicted, the procedure is generating the entries in the database and giving each entry a unique Id. TheId is a database identification column that automatically increments. The entities, however, are not updated with new Ids. As a result, after the initial savechanges, all entities still have values of 0.

How can I update these entities with recently generated Ids?

Inside foreach I tried refreshing the loop as

   _dbContext.Entry<OcrFile>(entity).ReloadAsync().ConfigureAwait(false);

but, it didn't reload.

1
1
3/31/2017 3:34:46 AM

Popular Answer

Resolved!!. Using eager loading, I must load entitiesToList() or ToArray() prior to passing them onAddRange method

    var entities = request.Select(x => new MyEntity()
    {
        FileName = x.FileName,                
        Status = Status.Downloading                
    }).ToList();

Although I'm not certain it is an EF problem, I did make a separate SO thread for that query.

1
5/23/2017 11:46:24 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow