简体   繁体   English

EF Core 3.1 不允许对枚举属性进行包含搜索

[英]EF Core 3.1 does not allow Contains search on Enum property

I'm trying to do a contains search on enum property in my DbSet and EF Core 3.1 throws the below error我正在尝试对我的DbSet中的enum属性进行包含搜索,而 EF Core 3.1 会引发以下错误

The LINQ expression 'DbSet.Where(d => d.Position.ToString().Contains("acc"))' could not be translated.无法翻译 LINQ 表达式 'DbSet.Where(d => d.Position.ToString().Contains("acc"))'。 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()以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估

Entity:实体:

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

Enum - Position:枚举 - Position:

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
}

DbContext:数据库上下文:

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>();
    }
}

When I query the table as follows I'm getting the error当我按如下方式查询表时,出现错误

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

The Position is of type NVARCHAR(MAX) in my database. Position 在我的数据库中属于NVARCHAR(MAX)类型。

在此处输入图像描述

在此处输入图像描述

This is not possible?这是不可能的? If so please can you help me with explanation?如果是这样,你能帮我解释一下吗?

This issue has been logged in efcore github repo and here is the workaround for this now.此问题已记录在efcore github 存储库中,这是现在的解决方法。 The enum property needs to be casted into object and then to string enum属性需要先转换成object string

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

Hope this helps someone out there.希望这可以帮助那里的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM