putting trim statement in LINQ

Anjali Agarwal 1,386 Reputation points
2024-04-12T01:07:44.42+00:00

I have the employee numbers in the database starting stored this way

EmployeeNumber
E123456
E999999
E666666
E111111

I want to write a LINQ statement to match the database EmployeeNumber with employeeId that is passed from web. I wrote the LINQ like this:

 _akContext.EmployeeInfos.Where(e => e.EmployeeNumber.TrimStart('E') == employeeId).OrderBy(e => e.EmployeeInfoId).Select(e => e.EmployeeInfoId).ToList();

With the above LINQ statement, I keep getting an error saying:

The LINQ expression 'DbSet<EmployeeInfo>()

.Where(e => e.EmployeeNumber.TrimStart(E) == __TrimStart_0)' could not be translated
```below is the screenshot:

![User's image](/api/attachments/a76a029e-307c-4571-8af8-12fac6863195?platform=QnA)

how can I compare both employeeId and EmployeeNumber in LINQ

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,234 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,364 questions
0 comments No comments
{count} votes

Accepted answer
  1. hossein jalilian 4,040 Reputation points
    2024-04-12T02:10:22.8633333+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    The TrimStart method is not supported in LINQ to SQL because it cannot be translated to SQL.

    You can achieve the same result by using the SqlFunctions class, specifically the SqlFunctions.PatIndex method, which simulates the functionality of TrimStart in LINQ to SQL.

    _akContext.EmployeeInfos.Where(e => e.EmployeeNumber.Substring(SqlFunctions.PatIndex("%[^E]%", e.EmployeeNumber) - 1) == employeeId)
        .OrderBy(e => e.EmployeeInfoId)
        .Select(e => e.EmployeeInfoId)
        .ToList();
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful