1

I have an SQL Server table:

ID | Code | Name
 1 | AS   | Andrew Smith
 2 | RA   | Ryan Andrews
 3 | ZS   | Zach Simmons

I want to find records where the starting of a code or the starting of the first or the last name in the Name column matches with a keyphrase. For instance, if the keyphrase is 'A', it should return:

 1 | AS   | Andrew Smith
 2 | RA   | Ryan Andrews

since the Code and First name of Andrew Smith matches with 'A' and the Last name of Andre Ryan matches with 'A'.

The query I have so far is:

 var keyphrase = 'aa';
 var employees = await (from e in _dbContext.Employee
                              where EF.Functions.Like(e.Code, $"{keyphrase}%")
                              orderby e.Code ascending
                              select e).ToListAsync();

This works well for searching against the Code. But I am not sure how to match the keyphrase against the first and last name in the name column. Again, I do not want to do a Contains but a StartsWith.

I am using EF core 3.1.

Any help is appreciated.

3
  • Linq to Sql is not Entity Framework, you might consider changing your question title and tags.
    – Crowcoder
    Jun 19, 2020 at 18:20
  • @Crowcoder Removed the tag. Thanks! Jun 19, 2020 at 18:21
  • You cannot use StartWIth for the last name since it's not at the start. You might want to consider splitting the first and last names into separate columns.
    – juharr
    Jun 19, 2020 at 18:34

3 Answers 3

1

Assuming you are using space (" ") before each term you want to check, then you can use the following trick:

where EF.Functions.Like(" " + e.Name, "% " + keyphrase + "%")

Note the space prepended to both column value and keyphrase. The space before the column is to handle keyphrase at start of the column value.

Alternatively, you can use 2 separate conditions for matching start and intermediate terms:

where EF.Functions.Like(e.Name, keyphrase + "%")
   || EF.Functions.Like(e.Name, "% " + keyphrase + "%")
1
  • Exactly what I was looking for! Jun 22, 2020 at 8:47
0

Here is a Nuget package way, or you can grab the source from Git Hub if you want the classes:

Nuget: DataJuggler.UltimateHelper.Core

using DataJuggler.Core.UltimateHelper;
using DataJuggler.Core.UltimateHelper.Objects;

// set the text
string text = "For a good night's sleep before bed, avoid caffiene.";

// split into lines if needed
List<TextLine> lines = WordParser.GetTextLines(text);

// verify the lines exist and have one or more items
if (ListHelper.HasOneOrMoreItems(lines))
{
    // Iterate the collection of TextLine objects
    foreach (TextLine textLine in lines)
    {
        // get the words
        List<Word> words = WordParser.GetWords(textLine.Text);

        // If the words collection exists and has one or more items
        if (ListHelper.HasOneOrMoreItems(words))
        {
            // Iterate the collection of Word objects
            foreach (Word word in words)
            {
                if (word.Text.ToLower().StartsWith("a"))
                {   
                    // do something for a
                }
                else if (word.Text.ToLower().StartsWith("b"))
                {   
                    // do something else for b
                }
                else if (word.Text.ToLower().StartsWith("c"))
                {   
                    // do something else for c
                }
            }
        }
    }
}

If you don't have multiple lines, you can skip the parsing lines part, but I have used this class for years and love it.

Full source code is on Nuget: https://github.com/DataJuggler/DataJuggler.UltimateHelper.Core

5
  • Just know that using a technique like this would require pulling the entire table to the client.
    – Crowcoder
    Jun 19, 2020 at 18:35
  • Will I will be able to use this in a LINQ query? LINQ complains about translating string operations like StartsWith() at runitme that lead me to use EF.Functions in the first place. Jun 19, 2020 at 18:38
  • @Crowcoder I want to avoid materializing the entire set since I am working with a lot of records and I want to do this on more than one dataset in the API call. Jun 19, 2020 at 18:51
  • @PrashantTiwari, yes I figured which is why I made the comment. I'm hoping someone with more EF kung-fu than me will answer. The problem is writing an expression that the provider can translate into SQL and if you know SQL, string manipulation is somewhat primitive compared to the APIs in C#.
    – Crowcoder
    Jun 19, 2020 at 18:53
  • @Crowcoder Thanks a lot. I will consider this as a last resort. Meanwhile I think I can figure out an SQL LIKE query to do the same and use it in the EF.Functions method. Once again, much appreciated brother. Jun 19, 2020 at 18:59
0

StartsWith should work with EF Core - it is translated to SQL LIKE with a trailing %. I would suggest using it and Contains:

var keyphrase = 'aa';
var employees = await (from e in _dbContext.Employee
                       where e.Code.StartsWith(keyphrase) || e.Name.StartsWith(keyphrase) || e.Name.Contains($" {keyphrase}")
                       orderby e.Code ascending
                       select e).ToListAsync();
1
  • If StartsWith is not translate at least in the latest nightly builds that is a new low for the EfCore team - this is like a standard opertion if anything. It is possibly and likely this isa fault in the 3.1 version because that one is abhorrent in the sql siide handling.
    – TomTom
    Jun 20, 2020 at 10:34

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.