diff --git a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs index 956e9b21955..deed78afc2e 100644 --- a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs @@ -214,7 +214,10 @@ protected override Expression VisitMember(MemberExpression memberExpression) && innerExpression != null && memberExpression.Member.Name == nameof(ICollection.Count) && memberExpression.Expression.Type.GetInterfaces().Append(memberExpression.Expression.Type) - .Any(e => e.IsGenericType && e.GetGenericTypeDefinition() == typeof(ICollection<>))) + .Any(e => e.IsGenericType + && (e.GetGenericTypeDefinition() is Type genericTypeDefinition + && (genericTypeDefinition == typeof(ICollection<>) + || genericTypeDefinition == typeof(IReadOnlyCollection<>))))) { var innerQueryable = UnwrapCollectionMaterialization(innerExpression); diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs index 90db5cc757e..29f69678271 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs @@ -324,5 +324,73 @@ public PhotoBlog() public int NumberOfPhotos { get; set; } } + + [ConditionalTheory] + [MemberData(nameof(IsAsyncData))] + public virtual async Task Count_member_over_IReadOnlyCollection_works(bool async) + { + var contextFactory = await InitializeAsync(seed: c => c.Seed()); + using var context = contextFactory.CreateContext(); + + var query = context.Authors + .Select(a => new + { + BooksCount = a.Books.Count + }); + + var authors = async + ? await query.ToListAsync() + : query.ToList(); + + Assert.Equal(3, Assert.Single(authors).BooksCount); + } + + protected class Context26433 : DbContext + { + public Context26433(DbContextOptions options) + : base(options) + { + } + + public DbSet Books { get; set; } + public DbSet Authors { get; set; } + + public void Seed() + { + + base.Add(new Author26433 + { + FirstName = "William", + LastName = "Shakespeare", + Books = new List + { + new() {Title = "Hamlet"}, + new() {Title = "Othello"}, + new() {Title = "MacBeth"} + } + }); + + SaveChanges(); + } + } + + protected class Author26433 + { + [Key] + public int AuthorId { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public IReadOnlyCollection Books { get; set; } + } + + protected class Book26433 + { + [Key] + public int BookId { get; set; } + public string Title { get; set; } + public int AuthorId { get; set; } + public Author26433 Author { get; set; } + } + } }