How to do SQL Like % in Linq?

2018-12-31 17:18发布

I have a procedure in SQL that I am trying to turn into Linq:

SELECT O.Id, O.Name as Organization
FROM Organizations O
JOIN OrganizationsHierarchy OH ON O.Id=OH.OrganizationsId
where OH.Hierarchy like '%/12/%'

The line I am most concerned with is:

where OH.Hierarchy like '%/12/%'

I have a column that stores the hierarchy like /1/3/12/ for example so I just use %/12/% to search for it.

My question is, what is the Linq or .NET equivalent to using the percent sign?

13条回答
路过你的时光
2楼-- · 2018-12-31 18:07

Use such code

try
{
    using (DatosDataContext dtc = new DatosDataContext())
    {
        var query = from pe in dtc.Personal_Hgo
                    where SqlMethods.Like(pe.nombre, "%" + txtNombre.Text + "%")
                    select new
                    {
                        pe.numero
                        ,
                        pe.nombre
                    };
        dgvDatos.DataSource = query.ToList();
    }
}
catch (Exception ex)
{
    string mensaje = ex.Message;
}
查看更多
永恒的永恒
3楼-- · 2018-12-31 18:07

In case you are not matching numeric strings, always good to have common case:

.Where(oh => oh.Hierarchy.ToUpper().Contains(mySearchString.ToUpper()))
查看更多
只若初见
4楼-- · 2018-12-31 18:14
.Where(oh => oh.Hierarchy.Contains("/12/"))

You can also use .StartsWith() or .EndsWith().

查看更多
泪湿衣
5楼-- · 2018-12-31 18:14
System.Data.Linq.SqlClient.SqlMethods.Like("mystring", "%string")
查看更多
皆成旧梦
6楼-- · 2018-12-31 18:16

Use this:

from c in dc.Organization
where SqlMethods.Like(c.Hierarchy, "%/12/%")
select *;
查看更多
低头抚发
7楼-- · 2018-12-31 18:16

I'm assuming you're using Linq-to-SQL* (see note below). If so, use string.Contains, string.StartsWith, and string.EndsWith to generate SQL that use the SQL LIKE operator.

from o in dc.Organization
join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
where oh.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

or

from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

Note: * = if you are using the ADO.Net Entity Framework (EF / L2E) in .net 3.5, be aware that it will not do the same translation as Linq-to-SQL. Although L2S does a proper translation, L2E v1 (3.5) will translate into a t-sql expression that will force a full table scan on the table you're querying unless there is another better discriminator in your where clause or join filters.
Update: This is fixed in EF/L2E v4 (.net 4.0), so it will generate a SQL LIKE just like L2S does.

查看更多
登录 后发表回答