LINQ to Entity, using a SQL LIKE operator

前端 未结 3 766
[愿得一人]
[愿得一人] 2021-01-04 08:50

I have a LINQ to ENTITY query that pulls from a table, but I need to be able to create a \"fuzzy\" type search. So I need to add a where clause that searches by lastname IF

相关标签:
3条回答
  • 2021-01-04 09:17

    Add your "select new" to the query only after you append your "Where" clause.

    Hence append your select clause using object call syntax as you did with the where clause.

    Untested, please excuse small errors, but the general concept would be....

       using( someContent sc = new someContent())
       {
          var query = sc.Member.OrderBy( i => i.LastName)
                        .ThenBy( i => i.FirstName);
    
          sLastName = formCollection["FuzzyLastName"].ToString();
    
          if (!String.IsNullOrEmpty(sLastName))
              query = query.Where(ln => ln.LastName.Contains(sLastName));
    
          query = query.Select( i => new
                    {
                        FirstName = i.FirstName,
                        LastName = i.LastName,
    
                    });
        }
    
    0 讨论(0)
  • 2021-01-04 09:34
    SELECT mem.LastName, mem.FirstName FROM Members mem WHERE mem.LastName = 'xxx'
    

    That means that you want the last name to be equal to 'xxx'. What you write in your above post is that the lastname should contain 'xxx'.

    To get it to equal you should write:

    if (!String.IsNullOrEmpty(sLastName))
       query = query.Where(ln => ln.LastName == sLastName);
    

    Perhaps you should look at ignore case:

    if (!String.IsNullOrEmpty(sLastName))
       query = query.Where(ln => ln.LastName.Equals(sLastName, StringComparison.InvariantCultureIgnoreCase));
    
    0 讨论(0)
  • 2021-01-04 09:38

    I think you want to use the Contains() function of the string parameter like this:

    var query = from mem in context.Member
        where mem.LastName.Contains("xxx")
        orderby mem.LastName, mem.FirstName
        select new
        {
            FirstName = mem.FirstName,
            LastName = mem.LastName,
        };
    

    I think you can also use StartsWith() and EndsWith() which would be equivalent to the SQL 'xxx%' and '%xxx" respectively.

    0 讨论(0)
提交回复
热议问题