EF Core 3.1 不允许在 Enum 属性 上进行包含搜索

EF Core 3.1 does not allow Contains search on Enum property

我正在尝试在我的 DbSet 中对 enum 属性 进行包含搜索,而 EF Core 3.1 抛出以下错误

The LINQ expression 'DbSet .Where(d => d.Position.ToString().Contains("acc"))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

实体:

public class DemoEntity
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Position Position { get; set; }
}

枚举 - 位置:

public enum Position
{
    [Display(Name = "Accountant")]
    Accountant,
    [Display(Name = "Chief Executive Officer (CEO)")]
    ChiefExecutiveOfficer,
    [Display(Name = "Integration Specialist")]
    IntegrationSpecialist,
    [Display(Name = "Junior Technical Author")]
    JuniorTechnicalAuthor,
    [Display(Name = "Pre Sales Support")]
    PreSalesSupport,
    [Display(Name = "Sales Assistant")]
    SalesAssistant,
    [Display(Name = "Senior Javascript Developer")]
    SeniorJavascriptDeveloper,
    [Display(Name = "Software Engineer")]
    SoftwareEngineer
}

数据库上下文:

public class DemoDbContext : DbContext
{
    public DemoDbContext(DbContextOptions options)
        : base(options) { }

    public DbSet<DemoEntity> Demos { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<DemoEntity>()
            .Property(e => e.Position)
            .HasConversion<string>();
    }
}

当我按如下方式查询 table 时,出现错误

try
{
    var test = await _context.Demos.Where(x => x.Position.ToString().Contains("acc")).ToListAsync();
}
catch (System.Exception e)
{
    //throw;
}

职位在我的数据库中属于 NVARCHAR(MAX) 类型。

这不可能吧?如果是这样,你能帮我解释一下吗?

此问题已记录在 efcore github repo 中,现在这里是解决方法。 enum 属性 需要转换为 object 然后转换为 string

var test = await _context.Demos.Where(x => ((string) object)x.Position).Contains("acc")).ToListAsync();

希望这对那里的人有所帮助。