dotnet / dotnet/docs

For EF Core, converting Enumerable.Count() to .Count may cause problems

Open
#24,735 3 comments 0 reactions 0 assignees View on GitHub
dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
15h 21m
Merged PRs (30d)
370

Description

It would be good to mention that using `Length/Count` property instead of `Enumerable.Count()` may cause issues when using it as part of Entity Framework query as it will change where the count is executed (client for properties, server for function call)

For example, in the following code, the query1 works while query2 throws `NullReferenceException`:

```CSharp
var query1 = Contracts
.AsNoTracking()
.Select(c => new {
Id = c.Id,
UsersCount = c.Users.Count()
});

var query2 = Contracts
.AsNoTracking()
.Select(c => new {
Id = c.Id,
UsersCount = c.Users.Count
});
```

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: aa3a4825-9d3f-6ea4-e93c-82f34c1c1add
* Version Independent ID: d9c26240-07ee-e8f5-4c7c-e3ad3dbd9efd
* Content: [CA1829: Use Length/Count property instead of Enumerable.Count method (code analysis) - .NET](https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1829)
* Content Source: [docs/fundamentals/code-analysis/quality-rules/ca1829.md](https://github.com/dotnet/docs/blob/main/docs/fundamentals/code-analysis/quality-rules/ca1829.md)
* Product: **dotnet-fundamentals**
* GitHub Login: @mavasani
* Microsoft Alias: **mavasani**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.