Home > Software design >  How to use LIKE Operator in LINQ to Entity Framework
How to use LIKE Operator in LINQ to Entity Framework

Time:02-08

I'm using Entity Framework.

Problem: search a name that start with 'a' in a list of strings:

var likeQuery = from k in dbContext.Categories  
                where sqlMethod.Like(k.CategoryName, "a%" )  // name start with a 
                select k;
        
foreach (var item in likeQuery)
{
    Console.WriteLine(Item.);
}

CodePudding user response:

Do like this.

var result 
  = dbContext.Categories.Where(i => i.CategoryName.StartsWith("a")).ToList();

CodePudding user response:

If this is EF Core than the following can be used.

public static  List<Categories> CategoriesLike(string keyword)
{
    using var dbContext = new NorthwindContext();

    return dbContext.Categories.Where(category => 
        EF.Functions.Like(category.CategoryName, $"{keyword}%"))
        .ToList();
}
  •  Tags:  
  • Related