Skip to content

IReadOnlyCollection cannot be used with Contains Query #36262

Description

@EvgenyMuryshkin

Bug description

Hi,

When a class implements IReadOnlyCollection, it cannot be used for a Contains query.

Fails with exception.

System.InvalidOperationException: 'The LINQ expression 'DbSet<tstRawDbEntity>()
    .Where(t => __c1_0.Contains(t.Id))' could not be translated. Additional information: Translation of method 'EF8Perf904.IdsContainerAndReadOnlyCollection.Contains' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

Thanks,
Regards,
Evgeny.

Your code

Here is a sample IReadOnlyCollection implementation

    class IdsContainerAndReadOnlyCollection : IEnumerable<Guid>, IReadOnlyCollection<Guid>
    {
        HashSet<Guid> _ids = new HashSet<Guid>();

        public int Count => _ids.Count;

        public bool IsReadOnly => true;

        public void Add(Guid id)
        {
            _ids.Add(id);
        }

        public void Clear() => _ids.Clear();

        public bool Contains(Guid item) => _ids.Contains(item);

        public void CopyTo(Guid[] array, int arrayIndex) => _ids.CopyTo(array, arrayIndex);

        public bool Remove(Guid item) => _ids.Remove(item);

        public IEnumerator<Guid> GetEnumerator() => _ids.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => _ids.GetEnumerator();
    }


Test scenario

        [TestMethod]
        public void ReadOnlyCollectionQuery()
        {
            using (var ctx = Context)
            {
                var c1 = new IdsContainerAndReadOnlyCollection() { Guid.NewGuid() };
                var items1 = ctx.Raws.Where(r => c1.Contains(r.Id)).ToList();
            }
        }

Stack traces


Verbose output


EF Core version

9.0.6

Database provider

MSSQL

Target framework

.NET9

Operating system

Windows 11

IDE

VS 17.14.6

Activity

  1. cincuranet commented on Jun 19, 2025

    @cincuranet
    Contributor

    @EvgenyMuryshkin This is the same as we already discussed here and here.

  2. added this to the Backlog milestone on Jun 23, 2025
  3. modified the milestones: Backlog, 11.0.0 on Dec 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions