Home > Enterprise >  C# Entity Framework with LIKE
C# Entity Framework with LIKE

Time:11-10

I have an application with the following code:

string passedValue = "5";
results = db.procedure1
            .Where(c => c.User.Contains(passedValue))
            .OrderBy(o => o.User).ToList();

The data in the Users column looks like this:

 05621
 18763
 58763
 98599

When I run the code, the resulting list contains 05621, 58763, and 98599

Instead of a Contains, I would like to implement a Like. In other words, I want to retrieve each data record where User is LIKE "5%".

The resulting list should be:

 58763

How would I accomplish this?

Thanks!

CodePudding user response:

Replace the .Where() clause that you have with something like below:

string passedValue = "5";
results = db.procedure1
            .Where(c => EF.Functions.Like(c.User, $"%{passedValue}%"))
            .OrderBy(o => o.User).ToList();

CodePudding user response:

For LIKE "5%" we have StartsWith so you can do like this

string passedValue = "5";
results = db.procedure1
            .Where(c => c.User.StartsWith(passedValue))
            .OrderBy(o => o.User).ToList();

For LIKE "%5" we have EndsWith and LIKE "%5%" - Contains`

  • Related