Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How to add a new M-N relation in an Extended non-Abstract Entity? #8943


User avatar
0
SASIMEXICO created

Hi, I have extended a non-abstract entity "OrganizationUnits" and created "OrganizationUnitGT". It works fine adding new parameters such as "ExternalCode". Now I want to add a new relation, it is an M-N relation with my Entity "TeleWorkingAudit". But I have the following problem:

"*The instance of entity type 'OrganizationUnitGT' 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.
System.InvalidOperationException: The instance of entity type 'OrganizationUnitGT' 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.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Add(TEntity entity)
   at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.Insert(TEntity entity)
   at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.InsertAsync(TEntity entity)
   at Abp.Domain.Repositories.AbpRepositoryBase`2.InsertOrUpdateAsync(TEntity entity)
   at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at GenTime.AppService.TeleWorkingAuditAppService.CreateAsync(CreateTeleWorkingAuditDto input) in C:\Users\mmartinez5\Documents\gitsasi\gentime.backend\src\GenTime.Application\GenTime\AppService\TeleWorkingAuditAppService.cs:line 399
   at Abp.Authorization.AuthorizationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Auditing.AuditingInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Runtime.Validation.Interception.ValidationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at lambdamethod(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeNextActionFilterAsync&gt;g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeInnerFilterAsync&gt;g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextExceptionFilterAsync&gt;g__Awaited|250(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Add(TEntity entity)
   at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.Insert(TEntity entity)
   at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.InsertAsync(TEntity entity)
   at Abp.Domain.Repositories.AbpRepositoryBase`2.InsertOrUpdateAsync(TEntity entity)
   at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at GenTime.AppService.TeleWorkingAuditAppService.CreateAsync(CreateTeleWorkingAuditDto input) in C:\Users\mmartinez5\Documents\gitsasi\gentime.backend\src\GenTime.Application\GenTime\AppService\TeleWorkingAuditAppService.cs:line 399
   at Abp.Authorization.AuthorizationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Auditing.AuditingInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Runtime.Validation.Interception.ValidationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeActionMethodAsync&gt;g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)*".

Here I attach my code.

Entity - OrganizationUnitGT (extended from "OrganizationUnit")

namespace GenTime.Model
{
    /// <summary>
    /// Represents an extended organization unit in the system.
    /// </summary>
    public class OrganizationUnitGT : OrganizationUnit
    {
        public virtual string ExternalCode { get; set; }
        public ICollection<TeleWorkingAuditOrganizationUnitGT> TeleWorkingAuditOrganizationUnitGTs { get; set; }

        public OrganizationUnitGT()
        {
            TeleWorkingAuditOrganizationUnitGTs = new HashSet<TeleWorkingAuditOrganizationUnitGT>();
        }

    }
}

Entity - TeleWorkingAudit

namespace GenTime.Model
{
    public partial class TeleWorkingAudit : FullAuditedEntity, IMayHaveTenant
    {
        public TeleWorkingAudit()
        {
            TeleWorkingAuditApplications = new HashSet<TeleWorkingAuditApplication>();
            TeleWorkingAuditTeleWorkingControlGroups = new HashSet<TeleWorkingAuditTeleWorkingControlGroup>();
            TeleWorkingAuditUsers = new HashSet<TeleWorkingAuditUser>();
            TeleWorkingAuditOrganizationUnitGTs = new HashSet<TeleWorkingAuditOrganizationUnitGT>();
        }

        public int DesiredUse { get; set; }
        public int? RealUse { get; set; }
        public string DesiredTimeUse { get; set; }
        public long RealTimeUse { get; set; }
        public string UseTopDown { get; set; }

        public string FromHour { get; set; }
        public string ToHour { get; set; }
        public int[] DaySelected { get; set; }

        public int? TenantId { get; set; }

        public ICollection<TeleWorkingAuditApplication> TeleWorkingAuditApplications { get; set; }
        public ICollection<TeleWorkingAuditTeleWorkingControlGroup> TeleWorkingAuditTeleWorkingControlGroups { get; set; }
        public ICollection<TeleWorkingAuditUser> TeleWorkingAuditUsers { get; set; }
        public ICollection<TeleWorkingAuditOrganizationUnitGT> TeleWorkingAuditOrganizationUnitGTs { get; set; }
    }
}

MN Class - TeleWorkingAuditOrganizationUnitGT

namespace GenTime.Model
{
    public partial class TeleWorkingAuditOrganizationUnitGT
    {
        public int TeleWorkingAuditId { get; set; }
        public TeleWorkingAudit TeleWorkingAudit { get; set; }

        public long OrganizationUnitGTId { get; set; }
        public OrganizationUnitGT OrganizationUnitGT { get; set; }
    }
}

What am I doing wrong? What should modify or add?

Thanks in advance for your help.


5 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Could you also share your TeleWorkingAuditAppService.CreateAsync method ?

    Did you try to inherit TeleWorkingAuditOrganizationUnitGT from Entity class ?

  • User Avatar
    0
    SASIMEXICO created

    Hi,

    Add/Create m-n link ok.

            var organizationUnitListCall = await GetOrganizationUnits();
            var organizationUnitList = organizationUnitListCall.Items.ToList();
            for (int i = 0; i < input.OUs.Count; i++)
            {
                var organizationUnitDto = organizationUnitList.Where(x => x.Id == input.OUs[i]).FirstOrDefault();
                var organizationUnit = _objectMapper.Map<OrganizationUnitGT>(organizationUnitDto);
                organizationUnit.TenantId = teleWorkingAudit.TenantId;
                if (organizationUnit != null)
                    teleWorkingAudit.TeleWorkingAuditOrganizationUnitGTs.Add(new TeleWorkingAuditOrganizationUnitGT() { OrganizationUnitGT = organizationUnit, OrganizationUnitGTId = organizationUnit.Id });
            }
    

    ----> the error is here, when everything is saved

        await _teleWorkingAuditRepository.InsertOrUpdateAsync(teleWorkingAudit);
        
        
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Could you check the value of Id field for organizationUnit in below line for each item ? Is it 0 or different all the time ?

    var organizationUnit = _objectMapper.Map<OrganizationUnitGT>(organizationUnitDto);
    
  • User Avatar
    0
    SASIMEXICO created

    Hi,

    Is diferent all time...

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Then, it seems fine. Could you add code below to your DbContext class to see the detailed error message and conflicting key ?

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.EnableSensitiveDataLogging();
        // ...
    }