Mat*_*ell 376 .net t-sql linq linq-to-entities sql-like
我在SQL中有一个程序,我试图变成Linq:
SELECT O.Id, O.Name as Organization
FROM Organizations O
JOIN OrganizationsHierarchy OH ON O.Id=OH.OrganizationsId
where OH.Hierarchy like '%/12/%'
Run Code Online (Sandbox Code Playgroud)
我最关心的是:
where OH.Hierarchy like '%/12/%'
Run Code Online (Sandbox Code Playgroud)
我有一个存储层的列,例如/ 1/3/12,所以我只使用%/ 12 /%来搜索它.
我的问题是,Linq或.NET相当于使用百分号?
and*_*eer 536
.Where(oh => oh.Hierarchy.Contains("/12/"))
Run Code Online (Sandbox Code Playgroud)
你也可以使用.StartsWith()
或.EndsWith()
.
小智 246
用这个:
from c in dc.Organization
where SqlMethods.Like(c.Hierarchy, "%/12/%")
select *;
Run Code Online (Sandbox Code Playgroud)
Kri*_*erA 40
我假设您正在使用Linq-to-SQL*(请参阅下面的注释).如果是这样,请使用string.Contains,string.StartsWith和string.EndsWith生成使用SQL LIKE运算符的SQL.
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 }
Run Code Online (Sandbox Code Playgroud)
要么
from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }
Run Code Online (Sandbox Code Playgroud)
注意: *=如果您在.net 3.5中使用ADO.Net实体框架(EF/L2E),请注意它不会执行与Linq-to-SQL相同的转换.尽管L2S执行了正确的转换,但L2E v1(3.5)将转换为t-sql表达式,该表达式将强制对您要查询的表进行全表扫描,除非在where子句或联接过滤器中有另一个更好的鉴别器.
更新:这在EF/L2E v4(.net 4.0)中得到修复,因此它将像L2S一样生成SQL LIKE.
rob*_*rtz 27
如果您使用的是VB.NET,那么答案就是"*".这是你的where子句的样子......
Where OH.Hierarchy Like '*/12/*'
Run Code Online (Sandbox Code Playgroud)
注意:"*"匹配零个或多个字符.这是Like运算符的msdn文章.
那么indexOf也适合我
var result = from c in SampleList
where c.LongName.IndexOf(SearchQuery) >= 0
select c;
Run Code Online (Sandbox Code Playgroud)
.NET 核心现在有 EF.Functions.Like
var isMatch = EF.Functions.Like(stringThatMightMatch, pattern);
Run Code Online (Sandbox Code Playgroud)
小智 5
使用这样的代码
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;
}
Run Code Online (Sandbox Code Playgroud)