Using bannedsymbols analyzer to disallow sync methods for materializing IQueryables

56 views Asked by At

We are using Entity Framework for communication with the database. Now we want to make sure we always use the async interface for materializing queryables. So we want to make sure we use ToArrayAsync instead of ToArray, ToDictionaryAsync instead of ToDictionary etc.

Now we are already using the banned symbols analyzer package from Microsoft to avoid using some symbols (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md)

I can create a rule in the BannedSymbols.txt file to avoid using ToArray altogether using:

M:System.Linq.Enumerable.ToArray``1(System.Collections.Generic.IEnumerable{``0});Don't use ToArray, use ToArrayAsync instead

However, I only want to ban the ToArray extension when being called on an IQueryable type. I can't figure out the id string format to use for this. (https://github.com/dotnet/csharpstandard/blob/standard-v6/standard/documentation-comments.md#d42-id-string-format).

Is this even possible?

1

There are 1 answers

0
nvoigt On

It seems the extension can only ban the use of certain methods. You cannot add context around those methods.

For example you could forbid the Skip method from Enumerable but you cannot differentiate based on context, so you cannot say you want to allow Skip, but only on List<T>, not on Array. Because it is the same method that is called.

I'm sure it is possible with Roslyn, but not with that specific analyzer.