Skip to content

TargetInvocationException when using Contains with non nullable value types with HasConversion #3919

Description

@henriquewr

Almost the same as #3842

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

System.ArgumentException: 'Expression of type 'System.Int32' cannot be used for parameter of type 'System.Nullable`1[System.Int32]' (Parameter 'arg0')'

    System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(System.Reflection.MethodBase, System.Linq.Expressions.ExpressionType, System.Linq.Expressions.Expression, System.Reflection.ParameterInfo, string, string, int)
    System.Linq.Expressions.Expression.Invoke(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)
    System.Linq.Expressions.Expression.Invoke(System.Linq.Expressions.Expression, System.Collections.Generic.IEnumerable<System.Linq.Expressions.Expression>)
    System.Reflection.MethodBaseInvoker.InvokeWithOneArg(object, System.Reflection.BindingFlags, System.Reflection.Binder, object[], System.Globalization.CultureInfo)

repro:

public static async Task Main(string[] args)
{
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseNpgsql()
        .Options;

    int[] numbers = new int[] { 1, 2 };

    using var context = new AppDbContext(options);

    var result = await context.Entities.Where(x => x.Num.HasValue && numbers.Contains(x.Num.Value)).ToListAsync();
}

public class AppDbContext(DbContextOptions options) : DbContext(options)
{
    public DbSet<SomeEntity> Entities { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.Entity<SomeEntity>().Property(s => s.Num)
            .HasConversion(
                v => v.HasValue ? v.Value.ToString().ToLower() : null,
                v => v == null ? null : int.Parse(v));

    public class SomeEntity
    {
        public int Id { get; set; }
        public int? Num { get; set; }
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions