InvalidOperationException:无法跟踪实体的实例-EF Core

时间:2019-06-11 13:46:54

标签: c# entity-framework-core

我试图在使用EF Core时以一对多关系将数据保存在多个表中。当我这样做时,会出现以下错误:

  

InvalidOperationException:无法跟踪实体类型'OrganizationGroupEntity'的实例,因为已经跟踪了另一个具有相同的{'Id'}键值的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看冲突的键值。

这是我的代码:

请求模型:

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; }
}

实体模型:

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");
}

存储库:

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 :(得分:0)

事实证明,当我获取当前的groupEntities以便找出要删除的内容时,我正在对该表发起跟踪。将AsNoTracking()添加到GetOrganizationGroups解决了我的问题。像这样:

private async Task<IEnumerable<OrganizationGroupEntity>> GetOrganizationGroups(int organizationId)
{
    return await _context.OrganizationGroups
        .AsNoTracking()
        .Where(e => e.OrganizationId == organizationId)
        .OrderBy(e => e.Order)
       .ToListAsync();
}