Skip to content

Failure when during array value conversion over nullable element type with non-nullable user conversion lambda #2189

Closed

Description

@hindams

While doing the net 6 upgrade from netcore 3.1, I ran into this issue:

public class Entity
{
    public EnumType? EnumProperty { get; set; }
}

public List<EnumType?> LinkingAttributeTypes => new List<EnumType?>
{
    EnumType.SomeValue,
};

var result = this.db.Entities.Where(e => LinkingAttributeTypes.Contains(e.EnumProperty));
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.ArgumentException: Expression of type 'Namespace.EnumType' cannot be used for parameter of type 'System.Nullable`1[Namespace.EnumType]' of method 'Void Add(System.Nullable`1[Namespace.EnumType])' (Parameter 'arg0')
 
  at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression arg0)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.ValueConversion.NpgsqlArrayConverter`2.ArrayConversionExpression[TInput,TOutput](LambdaExpression elementConversionExpression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.ValueConversion.NpgsqlArrayConverter`2.FromArrayProviderExpression(LambdaExpression elementFromProviderExpression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.ValueConversion.NpgsqlArrayConverter`2..ctor(ValueConverter elementConverter)

Activity

  1. hindams commented on Dec 28, 2021

    @hindams
    Author

    After some digging, I think there's an issue here:

    Expression.Convert(p, inputElementType.UnwrapNullableType())),

    We're unwrapping the nullable type while converting the array, but the parameter of the expression seems to remain nullable.

    I tried this too but didn't solve it:
    var result = this.db.Entities.Where(e => LinkingAttributeTypes.Contains(e.EnumProperty.Value));

  2. hindams commented on Dec 29, 2021

    @hindams
    Author

    This is the easiest way I found to make it work, basically make sure none of the types are nullable

    var result = this.db.Entities.Where(e => LinkingAttributeTypes.Cast<EnumType>().Contains((EnumType )e.EnumProperty.Value));

    It doesn't make sense to make this change at our codebase to support this scenario.

  3. roji commented on Dec 29, 2021

    @roji
    Member

    Can you please submit a runnable code sample? The code below works fine for me on EF Core 6.0:

    Attempted repro
    class Program
    {
        public static async Task Main()
        {
            await using var ctx = new BlogContext();
            await ctx.Database.EnsureDeletedAsync();
            await ctx.Database.EnsureCreatedAsync();
    
            var result = ctx.Entities.Where(e => LinkingAttributeTypes.Contains(e.EnumProperty)).ToList();
        }
    
        static List<EnumType?> LinkingAttributeTypes => new List<EnumType?>
        {
            EnumType.SomeValue,
        };
    }
    
    public class BlogContext : DbContext
    {
        public DbSet<Entity> Entities { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"Host=localhost;Username=test;Password=test")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Entity
    {
        public int Id { get; set; }
        public EnumType? EnumProperty { get; set; }
    }
    
    public enum EnumType
    {
        SomeValue
    }
  4. hindams commented on Dec 29, 2021

    @hindams
    Author

    I was missing the string to enum conversion, It might be part of the problem here:

    using System;
    using System.Collections.Immutable;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
    using Microsoft.Extensions.Logging;
    using Npgsql;
    using Npgsql.NameTranslation;
    
    namespace EFCore.Console;
    
    class Program
    {
        public static async Task Main()
        {
            await using var ctx = new BlogContext();
            await ctx.Database.EnsureDeletedAsync();
            await ctx.Database.EnsureCreatedAsync();
    
            var result1 = ctx.Entities.Where(e => Attributes.Cast<EnumType>().Contains((EnumType)e.EnumProperty!)).ToList();
    
            var result2 = ctx.Entities.Where(e => Attributes.Contains(e.EnumProperty)).ToList();
        }
    
        static List<EnumType?> Attributes => new List<EnumType?>
        {
            EnumType.SomeValue,
        };
    }
    
    public class BlogContext : DbContext
    {
        private readonly INpgsqlNameTranslator nameTranslator = new NpgsqlSnakeCaseNameTranslator();
        private readonly ValueConverter<EnumType, string> valueConverter;
    
        public DbSet<Entity> Entities { get; set; } = null!;
    
        public BlogContext()
        {
            NpgsqlConnection.GlobalTypeMapper.MapEnum<EnumType>("enum_type");
    
            this.valueConverter = EnumToStringValueConverter<EnumType>();
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"Host=localhost;Database=efcore-test;Username=postgres;Port=5433")
                .LogTo(System.Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Entity>(entity =>
            {
                entity.Property(e => e.EnumProperty).HasConversion(this.valueConverter);
            });
    
            base.OnModelCreating(modelBuilder);
        }
    
        private ValueConverter<T, string> EnumToStringValueConverter<T>()
        {
            var databaseStringsToEnums = ImmutableDictionary.CreateRange(
                Enum.GetValues(typeof(T))
                    .Cast<T>()
                    .Select(t => new KeyValuePair<string, T>(this.nameTranslator.TranslateTypeName(t!.ToString()!), t))
            );
    
            return new ValueConverter<T, string>(
                t => this.nameTranslator.TranslateTypeName(t!.ToString()!),
                s => databaseStringsToEnums[s]
            );
        }
    }
    
    public class Entity
    {
        public int Id { get; set; }
        public EnumType? EnumProperty { get; set; }
    }
    
    public enum EnumType
    {
        SomeValue
    }
    
  5. hindams commented on Dec 29, 2021

    @hindams
    Author

    I tried ValueConverter<EnumType?, string> too, it didn't work but feel to try it, maybe I'm missing something.

  6. added a commit that references this issue on Dec 30, 2021
    74b5df8
  7. roji commented on Dec 30, 2021

    @roji
    Member

    Thanks @hindams, I can see the issue. I've submitted #2197 to fix this for 6.0.3.

  8. changed the title [-]System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.[/-] [+]Failure when during array value conversion over nullable element type with non-nullable user conversion lambda[/+] on Dec 30, 2021
  9. self-assigned this
    on Dec 30, 2021
  10. added this to the 6.0.3 milestone on Dec 30, 2021
  11. added 2 commits that reference this issue on Dec 30, 2021
    45d0739
    1678cda
  12. roji commented on Dec 30, 2021

    @roji
    Member

    Backported to 6.0.3 via 1678cda

  13. emadelwany commented on Dec 30, 2021

    @emadelwany

    Thanks @roji for an incredibly fast resolution! It's always a pleasure working with Npgsql.

  14. roji commented on Dec 30, 2021

    @roji
    Member

    My pleasure. You can grab the latest daily build from the patch feed to test and confirm this works (I'd be happy to know).

  15. hindams commented on Dec 30, 2021

    @hindams
    Author

    Thanks @roji for the fast fix, I tried the patch feed for this specific scenario and it worked, will update you if I found any other related issues.

  16. roji commented on Dec 31, 2021

    @roji
    Member

    Great, thanks for the confirmation!

  17. hindams commented on Jan 21, 2022

    @hindams
    Author

    @roji is there any update on 6.0.3 release?

  18. added theissue type on Jun 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions