Search code examples
c#winformsef-core-7.0

Id could not be removed when attached multiple entities with the same Id


I have three class GdsReceptionBlackProduct, Employee and Customer

public partial class GdsReceptionBlackProduct
{
    public int Id { get; set; }
    public string? CreatedBy { get; set; }
    public virtual Employee? CreatedByNavigation { get; set; }
}

public void Configure(EntityTypeBuilder<GdsReceptionBlackProduct> entity)
{
    entity.HasOne(d => d.CreatedByNavigation).WithMany(p => p.CreatedBy)
    .HasPrincipalKey(p => p.IdEmployee)
    .HasForeignKey(d => d.CreatedBy)
    .HasConstraintName("GDSReceptionBlackProduct_Employee_CreatedBy");
    entity.Navigation(e => e.CreatedByNavigation).AutoInclude();
}  

public partial class Employee
{
    public string IdEmployee { get; set; } = null!;
    public int? FkCountry { get; set; }
    public virtual Country Country { get; set; }
    public virtual ICollection<GdsReceptionBlackProduct> CreatedBy { get; } = new List<GdsReceptionBlackProduct>();
}
public void Configure(EntityTypeBuilder<Employee> entity)
{
    entity.HasOne(d => d.Country)
        .WithMany(p => p.Employees)
        .HasForeignKey(d => d.FkCountry)
        .HasConstraintName("FK_Employee_Country");
    entity.Navigation(e => e.Country).AutoInclude();
}
public partial class Customer
{
    public int? Fkcountry { get; set; }
    public virtual Country? Country { get; set; }
    public virtual ICollection<GdsReceptionBlackProduct> GdsReceptionBlackProduct { get; } = new List<GdsReceptionBlackProduct>();
}
public void Configure(EntityTypeBuilder<Customer> entity)
{
    entity.Navigation(e => e.Country).AutoInclude();
}

I am using unit of work with repository pattern and DI so in FrmGDSReceptionBlackProduct I use it like this

public FrmGDSReceptionBlackProduct(GdsReceptionBlackProductService gdsReceptionBlackProductService,
                                       CustomerService customerService)
{
    InitializeComponent();
    this.gdsReceptionBlackProductService = gdsReceptionBlackProductService;
    this.customerService = customerService;
}

When I try to remove GdsReceptionBlackProduct

await gdsReceptionBlackProductService.RemoveGdsReceptionBlackProductAsync(Convert.ToInt32(txtID.Text));
public virtual async Task<bool> RemoveAsync(object id)
{
    T? exist = await dbSet.FindAsync(id);
    if (exist == null) throw new ArgumentNullException($"{nameof(RemoveAsync)} entity must not be null");
    dbSet.Remove(exist);
    return true;
}

I get this error message

id could not be removed: The instance of entity type 'Country' cannot be tracked because another instance with the key value '{IdCountry: 1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

when I comment the below line of code

entity. Navigation(e => e.CreatedByNavigation).AutoInclude();

and I trying to remove the GdsReceptionBlackProduct entity it removed successfully.
I am using AutoInclude to show the properties names in grid view.
All CRUD operations are in the same form.
How can I fix this issue?
Update
this is the constructor of my generic repository

public class GenericRepository<T> : IGenericRepository<T>, IDisposable where T : class

{
    protected SIMContext _context;
    internal DbSet<T> dbSet;
    public GenericRepository(SIMContext context)
    {
        _context = context;
        _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        dbSet = context. Set<T>();
    }

Solution

  • Thanks to Richard Deeming I get the answer