efcore.pg icon indicating copy to clipboard operation
efcore.pg copied to clipboard

Accessing private array field with `EF.Property<T[]>(obj, "name")` fails if T is enum

Open sleepwalkerffs opened this issue 4 years ago • 8 comments

As described in the title, accessing a private array field of a domain object fails with an exception. There is an easy workaround (you retrieve it as int[]) but I was not sure is this was intended to break. The code below works for version 6.0.3 but does break for version 6.0.4 and onwards. Program.cs:

using Microsoft.EntityFrameworkCore;

var db = "test";
static string GetConnection(string db)
{
    return $"Host=localhost;Port=8432;Database={db};User ID=postgres;Password=password";
}

using var context = OpenContext(GetConnection(db));
context.Database.EnsureDeleted();
context.Database.EnsureCreated();

for (var i = 0; i < 5; i++)
{
    var p = new Person();
    p.AddGrade(Grade.A);
    p.AddGrade(Grade.B);
    p.AddGrade(Grade.F);
    await context.Persons.AddAsync(p);
    await context.SaveChangesAsync();
}

var allowedGrades = new List<Grade>() { Grade.A, Grade.B, Grade.F };
var persons = from person in context.Persons
              where allowedGrades.All(value => EF.Property<Grade[]>(person, "grades").Contains(value))
              select person;
var x = await persons.ToListAsync();
Console.WriteLine(x.Count);


SampleContext OpenContext(string connectionString)
{
    var builder = new DbContextOptionsBuilder<SampleContext>();
    builder.UseNpgsql(connectionString);

    return new SampleContext(builder.Options);
}

internal class SampleContext : DbContext
{
    public SampleContext(DbContextOptions options) : base(options) { }
    public DbSet<Person> Persons { get; set; } = null!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Person>().Property(x => x.Id).UseHiLo("Person_Sequence");
        modelBuilder.Entity<Person>().Property("grades").HasColumnName(nameof(Person.Grades));
    }
}

internal class Person
{
    private Grade[] grades = Array.Empty<Grade>();

    public int Id { get; set; }
    public IReadOnlyList<Grade> Grades => grades;

    public void AddGrade(Grade grade)
    {
        grades = grades.Append(grade).ToArray();
    }
}

public enum Grade
{
    A = 0,
    B = 1,
    C = 3,
    D = 4,
    F = 5
}

csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.4" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.4" />
  </ItemGroup>
</Project>

Exception thrown:

System.InvalidCastException
  HResult=0x80004002
  Message=Object must implement IConvertible.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType)
   at Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter`2.Sanitize[T](Object value)
   at Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter`2.<>c__DisplayClass4_0`2.<SanitizeConverter>b__1(Object v)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping.CreateParameter(DbCommand command, String name, Object value, Nullable`1 nullable)
   at Microsoft.EntityFrameworkCore.Storage.Internal.TypeMappedRelationalParameter.AddDbParameter(DbCommand command, Object value)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBase.AddDbParameter(DbCommand command, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateDbCommand(RelationalCommandParameterObject parameterObject, Guid commandId, DbCommandMethod commandMethod)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.<ExecuteReaderAsync>d__19.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.<InitializeReaderAsync>d__19.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.<MoveNextAsync>d__18.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Program.<<Main>$>d__0.MoveNext() in C:\playground\Testing\Test\Stuff\Program.cs:line 27

  This exception was originally thrown at this call stack:
    System.Convert.ChangeType(object, System.Type, System.IFormatProvider)
    System.Convert.ChangeType(object, System.Type)
    Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping.CreateParameter(System.Data.Common.DbCommand, string, object, bool?)
    Microsoft.EntityFrameworkCore.Storage.Internal.TypeMappedRelationalParameter.AddDbParameter(System.Data.Common.DbCommand, object)
    Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBase.AddDbParameter(System.Data.Common.DbCommand, System.Collections.Generic.IReadOnlyDictionary<string, object>)
    Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateDbCommand(Microsoft.EntityFrameworkCore.Storage.RelationalCommandParameterObject, System.Guid, Microsoft.EntityFrameworkCore.Diagnostics.DbCommandMethod)
    Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(Microsoft.EntityFrameworkCore.Storage.RelationalCommandParameterObject, System.Threading.CancellationToken)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    ...
    [Call Stack Truncated]

sleepwalkerffs avatar Jun 28 '22 09:06 sleepwalkerffs

What kind of error do you get?

NativBashari avatar Jun 28 '22 09:06 NativBashari

Sorry I forgot to post the stacktrace, i updated the issue

sleepwalkerffs avatar Jun 28 '22 10:06 sleepwalkerffs

I think that you need to use a collection instead of array. and you need to initialize the collection this way: var enumsCollection = Enum.GetValues(typeof(Grade)).Cast<Grade>(); Then try to run the query with this list.

NativBashari avatar Jun 28 '22 10:06 NativBashari

what should var enumsCollection = Enum.GetValues(typeof(Grade)).Cast<Grade>(); change? because this simply gives me a list of all the values available in the enum Grade. It works when I change private Grade[] grades = Array.Empty<Grade>(); to private List<Grade> grades = new(); but I was just curious why the array version breaks "all of a sudden"?

sleepwalkerffs avatar Jun 28 '22 11:06 sleepwalkerffs

OK, you do not need the GetValues method. but you need the Cast method. Try to add the Cast method to the initialization of the array.

NativBashari avatar Jun 28 '22 11:06 NativBashari

I really appriciate your effort and every suggestion you made will work but I am just wondering why this is not working anymore. I really just wanna know if this change was intended or if I discovered a bug. 😃

sleepwalkerffs avatar Jun 28 '22 17:06 sleepwalkerffs

Confirmed that this is a bug introduced in 6.0.4 as part of #2312.

However, the fix for #2406 makes this work again - this is another form of mixing arrays and lists that's covered by that issue. This fix has already been merged for 6.0.6, you can use package 6.0.6-ci.20220620T201659 or above from the stable feed until 6.0.6 is released.

roji avatar Jun 29 '22 10:06 roji

Duplicate of #2406

roji avatar Jun 29 '22 10:06 roji