dotnet / ef6

This is the codebase for Entity Framework 6 (previously maintained at https://entityframework.codeplex.com). Entity Framework Core is maintained at https://github.com/dotnet/efcore.

Home Page:https://docs.microsoft.com/ef/ef6

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

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:

  1. 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.

  1. 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)