InvalidOperationException: The instance of entity cannot be tracked - EF Core

c# entity-framework-core

Question

I am attempting to save date in multiple tables with a one-to-many relationship in using EF Core. When I do, I get this error:

InvalidOperationException: The instance of entity type 'OrganizationGroupEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

Here is my code:

Request model:

public class Organization
{
    public Organization()
    { }

    public Organization(OrganizationEntity organizationEntity, List<OrganizationGroupEntity> organizationGroupEntities)
    {
        Id = organizationEntity.Id;
        Name = organizationEntity.Name;
        Groups = ToList(organizationGroupEntities);
    }

    public int Id { get; set; }
    public string Name { get; set; }}
    public List<OrganizationGroup> Groups { get; set; }

    private List<OrganizationGroup> ToList(List<OrganizationGroupEntity> organizationGroupEntities)
    {
        return organizationGroupEntities.Select(
                entity => new OrganizationGroup(entity)
            ).ToList();
    }
}

public class OrganizationGroup
{
    public OrganizationGroup()
    { }

    public OrganizationGroup (OrganizationGroupEntity entity)
    {
        Id = entity.Id;
        Group = entity.Group;
    }

    public int Id { get; set; }
    public string Group { get; set; }
}

Entity models:

public class OrganizationEntity
{
    public OrganizationEntity()
    { }

    public OrganizationEntity(Organization model)
    {
        Id = model.Id;
        Name = model.Name;
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
}

public class OrganizationGroupEntity
{
    public OrganizationGroupEntity()
    { }

    public OrganizationGroupEntity(int organizationId, OrganizationGroup model)
    {
        Id = model.Id;
        OrganizationId = organizationId;
        Group = model.Group;
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int OrganizationId { get; set; }
    public string Group { get; set; }
}

dbContext:

public DbSet<OrganizationEntity> Organizations { get; set; }
public DbSet<OrganizationGroupEntity> OrganizationGroups { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<OrganizationEntity>()
        .ToTable("Organizations", "dbo");

    modelBuilder.Entity<OrganizationGroupEntity>()
        .ToTable("OrganizationGroups", "dbo");
}

repository:

public async Task<Organization> UpdateOrganization(Organization request)
{
    // Get the org entity
    var organizationEntity = new OrganizationEntity(request);

    // get the org groups entities
    var groupEntities = request.Groups
        .Select(
            group => new OrganizationGroupEntity(request.Id, group)
        ).ToList();

    // Get the group entities to remove
    var oldEntities = GetOrganizationGroups(request.Id);
    var entitiesToRemove = new List<OrganizationGroupEntity>();
    foreach (var oldEntity in oldEntities.Result)
    {
        if (!groupEntities.Any(e => e.Id == oldEntity.Id))
        {
            entitiesToRemove.Add(oldEntity);
        }
    }

    using (var transaction = _context.Database.BeginTransaction())
    {
        _context.Organizations.Update(organizationEntity);
        _context.OrganizationGroups.UpdateRange(groupEntities);        // <-- Fails here
        _context.OrganizationGroups.RemoveRange(entitiesToRemove);
        await _context.SaveChangesAsync();
        transaction.Commit();
    }

    return request;
}

private async Task<IEnumerable<OrganizationGroupEntity>> GetOrganizationGroups(int organizationId)
{
    return await _context.OrganizationGroups
        .Where(e => e.OrganizationId == organizationId)
        .OrderBy(e => e.Order)
        .ToListAsync();
}
1
0
6/11/2019 3:24:35 PM

Popular Answer

It turns out when I was getting the current groupEntities in order to fins out what to remove I was initiating tracking on that table. Adding AsNoTracking() to GetOrganizationGroups solved my issue. Like so:

private async Task<IEnumerable<OrganizationGroupEntity>> GetOrganizationGroups(int organizationId)
{
    return await _context.OrganizationGroups
        .AsNoTracking()
        .Where(e => e.OrganizationId == organizationId)
        .OrderBy(e => e.Order)
       .ToListAsync();
}
0
6/11/2019 4:04:43 PM


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