EF Core 3.1 不允许对 Enum 属性进行 Contains 搜索

fin*_*s10 7 c# enums entity-framework-core entity-framework-core-3.1

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

无法翻译 LINQ 表达式 'DbSet .Where(d => d.Position.ToString().Contains("acc"))'。以可翻译的形式重写查询,或者通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 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; }
}
Run Code Online (Sandbox Code Playgroud)

枚举 - 位置:

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
}
Run Code Online (Sandbox Code Playgroud)

数据库上下文:

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>();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

该职位是我的数据库中的类型NVARCHAR(MAX)

在此输入图像描述

在此输入图像描述

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

fin*_*s10 8

此问题已记录在efcore github 存储库中,现在是解决方法。该enum财产需要被铸造object,然后string

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

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