Skip to content

Commit

Permalink
Query: Convert IReadOnlyCollection.Count to Queryable.Count()
Browse files Browse the repository at this point in the history
Resolves #26437
  • Loading branch information
smitpatel committed Oct 28, 2021
1 parent 90f0808 commit dd70313
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,10 @@ protected override Expression VisitMember(MemberExpression memberExpression)
&& innerExpression != null
&& memberExpression.Member.Name == nameof(ICollection<int>.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);

Expand Down
68 changes: 68 additions & 0 deletions test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Context26433>(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<Book26433> Books { get; set; }
public DbSet<Author26433> Authors { get; set; }

public void Seed()
{

base.Add(new Author26433
{
FirstName = "William",
LastName = "Shakespeare",
Books = new List<Book26433>
{
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<Book26433> 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; }
}

}
}

0 comments on commit dd70313

Please sign in to comment.