EFCore Instance of join entity type cannot be tracked because another instance with the key value is already being tracked

System.InvalidOperationException: “The instance of entity type ‘JoinEntity’ cannot be tracked because another instance with the key value ‘{TestEntity1Id: 11, TestEntity2Id: 59}’ is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.”

I`ve recreated the error that occured in my project. For testing sakes I use InMemory provider. I have a simple N:N relationship with custom join entity and navigations to and from join entity:

namespace ConsoleApp2
{
    public class TestDbContext : DbContext
    {
        public DbSet<TestEntity1> TestEntity1 { get; set; }
        public DbSet<TestEntity2> TestEntity2 { get; set; }
        public DbSet<JoinEntity> JoinEntity { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseInMemoryDatabase("TestDB");
            optionsBuilder.EnableSensitiveDataLogging();
            optionsBuilder.LogTo(Console.WriteLine);
            optionsBuilder.EnableDetailedErrors();
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
     
            builder.Entity<TestEntity1>()
                .HasKey(x => x.Id);
            builder.Entity<TestEntity2>()
                .HasKey(x => x.Id);
            builder.Entity<TestEntity1>()
                .HasMany(e => e.TestEntity2List)
                .WithMany(e => e.TestEntity1List)
                .UsingEntity<JoinEntity>();
        }
    }
    public class TestEntity1
    {
        public int Id { get; set; }
        public List<TestEntity2> TestEntity2List { get; set; } = new();
        public List<JoinEntity> JoinEntityList { get; set; } = new();
    }
    public class TestEntity2 
    {
        public int Id { get; set; }
        public List<TestEntity1> TestEntity1List { get; set; } = new();
        public List<JoinEntity> JoinEntityList { get; set; } = new();
    }
    public class JoinEntity
    {
        public TestEntity1 TestEntity1 { get; set; }
        public TestEntity2 TestEntity2 { get; set; }
        public int TestEntity1Id { get; set; }
        public int TestEntity2Id { get;set; }
        public int Value { get; set; }
    }
}

For each instance of TestEntity1 3 instances of TestEntity2 are added into navigation collection. And for each relation, new instance of JoinEntity is created:

TestDbContext dbContext = new TestDbContext();


var entity1List = Enumerable.Range(1, 50)
    .Select(x => new TestEntity1 { Id = x })
    .ToList();

var entity2List = Enumerable.Range(1, 50)
    .Select(x => new TestEntity2 { Id = x + 52 })
    .ToList();

int numberOfBoundEntities = 3;
Random random = new Random();

foreach (var entity1 in entity1List)
{
    for (int i = 0; i < numberOfBoundEntities; i++)
    {
        TestEntity2 entity2 = entity2List[random.Next(0, entity2List.Count)];
        JoinEntity joinEntity = new() 
        { 
            Value = random.Next(),
            TestEntity1 = entity1,
            TestEntity2 = entity2,
            TestEntity1Id = entity1.Id,
            TestEntity2Id = entity2.Id,
        };

        entity1.TestEntity2List.Add(entity2);
        entity1.JoinEntityList.Add(joinEntity);

        entity2.TestEntity1List.Add(entity1);
        entity2.JoinEntityList.Add(joinEntity);
    }
}
dbContext.TestEntity1.AddRange(entity1List); **Here occurs the error**
dbContext.TestEntity2.AddRange(entity2List);
dbContext.SaveChanges();
Console.WriteLine(0);

I`ve tryed not to explicitly add instances of JoinEntity to collections of entity1 and entity2, but in this case EF generates new instances of JoinEntity (obvious)

All properties of JoinEntity are configured on convention so that’s definitely not the problem.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật