When inserting multiple entities and accessing a related entity using lazy loading, only one new entity is created in DB.
javierlatorrep opened this issue · comments
javierlatorre commented
Include your code
When inserting multiple entities and accessing a related entity using lazy loading, only one new entity is created in DB.
Steps to reproduce:
- When using EF in a project like this:
for (int i = 0; i < 20; i++) {
var entity = new Entity()
{
notUniqueField = "abc"
};
IQueryable<AnotherEntity> query = DBContext.Set<AnotherEntity>();
query = query.Where(anotherEntity => anotherEntity.Id == 1);
var anotherEntities = await query.ToListAsync();
// var relatedEntity = anotherEntities.FirstOrDefault()?.RelatedEntity; // Lazy loaded
await DBContext.Set<Entity>().AddAsync(entity);
await DBContext.SaveChangesAsync();
}
20 new rows are going to be added into the DB.
- Uncomment line
var relatedEntity = anotherEntities.FirstOrDefault()?.RelatedEntity;
and run again
Only one new entry (instead of 20) will be added in the DB.
Include provider and version information
EF version: 6.0.9
Database provider: SQL Server 12.0.2000.8
Target framework: .NET6
Operating system: Window 11 Enterprise 64-bit (10.0, Build 22621)
IDE: Microsoft Visual Studio Enterprise 2022 (64-bit) - Version 17.4.3
(Tested in .NET 7 & EF7, and it's still happening)