Skip to content

AmbiguousMatchException when selecting a property named “Item” using EF Core DbContext #936

@LorenzoFrancone

Description

@LorenzoFrancone

When projecting an anonymous type that includes a property called Item against an EF Core DbContext, System.Linq.Dynamic.Core throws an AmbiguousMatchException.

Environment

  • Target framework: net8.0
  • NuGet packages:
    • Microsoft.EntityFrameworkCore.InMemory 8.0.17
    • Microsoft.EntityFrameworkCore 8.0.17
    • System.Linq.Dynamic.Core 1.6.6

Example to Reproduce

// Program.cs
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace DynamicLinqEfCoreInMemory
{
    public class Record
    {
        public int Id { get; set; }
        public string Item { get; set; }
        public int Value { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public DbSet<Record> Records { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseInMemoryDatabase("TestDb");
        }
    }

    class Program
    {
        static void Main()
        {
            using var ctx = new AppDbContext();
            ctx.Records.AddRange(
                new Record { Item = "Alpha", Value = 1 },
                new Record { Item = "Beta", Value = 2 }
            );
            ctx.SaveChanges();

            try
            {
                var queryResult = ctx.Records.Select("new(Item, Value)"); // throws "AmbiguousMatchException"

                Console.WriteLine("projection succeeded.");
                foreach (var x in queryResult)
                {
                    Console.WriteLine($"  {x}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR: {ex.GetType().Name}: {ex.Message}");
            }
        }
    }
}

Actual Behavior

Running this code results in:

ERROR: AmbiguousMatchException: Ambiguous match found for '<>f__AnonymousType0`2 System.String Item'.

Expected Behavior

Selecting "new(Item, Value)" against an EF Core DbContext should bind to the entity’s Item property and return the projected anonymous objects without error.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions