Skip to content

Lazy loader throwing invalid operation exceptions #32390

@MoazAlkharfan

Description

@MoazAlkharfan

File a bug

Include your code

Assuming it's because of concurrent access to memory cached entities after they have been loaded and the DbContext has already been disposed.

Reproduction repository: https://github.com/MoazAlkharfan/efcore-issue-32390

Places to check:

  • TagsCacheService fetch data from db
  • Program mapped / endpoint
  • ServerRequest do get requests on the / endpoint

Include stack traces

For the first:

private bool IsLoading((object Entity, string NavigationName) navEntry)
=> (_isLoading ??= new List<(object Entity, string NavigationName)>())
.Contains(navEntry, EntityNavigationEqualityComparer.Instance);

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.Collections.Generic.List`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.Contains[TSource](IEnumerable`1 source, TSource value, IEqualityComparer`1 comparer)
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.LazyLoader.Load(Object entity, String navigationName)
   at Castle.DynamicProxy.AbstractInvocation.Proceed()

private void DoneLoading((object Entity, string NavigationName) navEntry)
{
for (var i = 0; i < _isLoading!.Count; i++)
{
if (EntityNavigationEqualityComparer.Instance.Equals(navEntry, _isLoading[i]))
{
_isLoading.RemoveAt(i);
break;
}
}
}

For the second:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.LazyLoader.Load(Object entity, String navigationName)
   at Castle.DynamicProxy.AbstractInvocation.Proceed()

Include provider and version information

EF Core version: 8.0
Database provider: (Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (.NET 8.0)
Operating system: Windows/Linux
IDE: (Visual Studio 2022 17.9)

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions