Search code examples
c#linq.net-coreentity-framework-core.net-8.0

.NET 8, EF Core query could not be translated when using a static collection/list as field


I'm curious about the following:

  • Why is EF Core unable to translate a static readonly ICollection<T> & static readonly IList<T> field into a query when using it inside of a .Contains()? When removing the static keyword it seems to execute the query just fine?
  • When using IEnumerable<T> This is not an issue, is this because of the different .Contains() that's being used?
  • This is only happening when the List/Collection are static, why is that so important here for the query to be translated?

I got this from the exception: https://learn.microsoft.com/en-us/ef/core/querying/client-eval but that doesn't really explain to me why this is happening only when using a static collection.

Let's say I have this database model when using EF Core:

public class Item
{
    public string Bar { get; set; }
    public string Foo { get; set; }
}

And in my class I have the following field (this can be a static readonly IList<T> or static readonly ICollection<T>):

private static readonly IList<string> AllowedFooCodes = new List<string>() { "ABC", "CED" };

My db class looks something like this:

public class SampleDataRepository : ISampleDataRepository
{
    private readonly ILogger<SampleDataRepository> _logger;
    private readonly SampleDataStore _sampleDataStore;

    // Can be IList or ICollection, exception will be thrown regardless.
    private static readonly IList<string> AllowedFooCodes = new List<string>() { "ABC", "CED" };
    
    public SampleDataRepository(SampleDataStore store, ILogger<SampleDataRepository> logger)
    {
        _sampleDataStore = store;
        _logger = logger;
    }
    
    public async Task<IEnumerable<Item>> GetItems()
    {
        _sampleDataStore.Items
                        .AsNoTracking()
                        .Where(item => AllowedFooCodes.Contains(item.foo))
                        .ToListAsync();
    }
}

I'm looking forward to your answers.


Solution

  • Seems like it was indeed a bug, looks like a Pull Request is already out for it as well: https://github.com/dotnet/efcore/pull/35029