具有int转换的Npgsql枚举数组在“包含”上引发InvalidCastException。

问题描述 投票:0回答:2
由于缺少枚举更改功能,我在npgsql中使用枚举到int转换为枚举数组。

型号:

public class TestEntity { public Guid Id { get; set; } public TestEnum[] Enums { get; set; } public TestEntity() { Enums = new TestEnum[0]; } } public enum TestEnum { NONE, FIRST, SECOND, THIRD }

上下文:

public class TestContext : DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<TestEntity>() .Property(x => x.Enums) .HasConversion( e => e.Cast<int>().ToArray(), e => e.Cast<TestEnum>().ToArray()); } }

[当我在LINQ表达式中从数据库读取实体或向db写入实体而没有“接触”数组属性时,一切工作正常-列在postgres中为integer []类型,并且映射正常工作。

但是,当我在enum []属性上使用“包含”函数时,它抛出InvalidCastException:“无法使用处理程序类型Int32Handler编写CLR类型Proj.TestEnum”。

示例:

var param = TestEnum.FIRST; var result = context.TestEntities! .Where(x => x.Enums.Contains(param)) .ToArray();

我缺少什么吗?

由于缺乏枚举更改功能,我正在使用numsql中的枚举数组进行枚举到int的转换。模型:公共类TestEntity {公共Guid ID {获取;组; } public TestEnum []枚举{get; ...

c# enums entity-framework-core npgsql ef-core-3.1
2个回答
0
投票
这是this issue的一种情况:使用值转换器块方法转换。

0
投票
如果我理解正确,有2种解决方案1.您可以在条件[]之前添加AsEnumerable()

var result = context.TestEntities! AsEnumerable().Where(x => x.Enums.Contains(param)) .ToArray();

© www.soinside.com 2019 - 2024. All rights reserved.