I'm trying to do a contains search on enum
property in my DbSet
and EF Core 3.1 throws the below error
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()
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:
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.
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. The enum
property needs to be casted into object
and then to string
var test = await _context.Demos.Where(x => ((string) object)x.Position).Contains("acc")).ToListAsync();
Hope this helps someone out there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.