Is there a way to cast in the `Where` part of an Entity Framework query?

c# casting entity-framework entity-framework-6 linq

Question

To be clear, I am not referring to performing a .Cast<T> on the results of an EF call.

I'm trying to implement a partial search on a number field.

When creating a SQL script, it is easy to convert a column to another data type:

SELECT Id
FROM Employees
WHERE CAST(Id AS VARCHAR) LIKE '%95%';

Is there any sort of equivalent in a LINQ query?

I can't modify the datatypes on the entity that I'm querying, and Id was just for demonstration purposes.

1
1
2/9/2017 3:25:26 PM

Accepted Answer

I do not know why ToString doesn't work, but this is what works for me. Without needing SqlFunctions:

            context.Employees.Where(emp => emp.Id.ToString().Contains("95")).ToList();
4
2/9/2017 3:21:22 PM

Popular Answer

You can use SqlFunctions.StringConvert:

var q = db.Employees
    .Where(emp => SqlFunctions.StringConvert((decimal) emp.Id).Contains("95"));


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow