我有以下 SQL:
select * from transaction_log where stoptime like '%2008%'
如何在 LINQ to SQL 语法中编写它?
我有以下 SQL:
select * from transaction_log where stoptime like '%2008%'
如何在 LINQ to SQL 语法中编写它?
如果要使用字面量方法,是这样的:
var query = from l in transaction_log
where SqlMethods.Like(l.stoptime, "%2008%")
select l;
另一种选择是:
var query = from l in transaction_log
where l.stoptime.Contains("2008")
select l;
如果是日期时间:
var query = from l in transaction_log
where l.stoptime.Year = 2008
select l;
该方法位于System.Data.Linq.SqlClient命名空间中
from x in context.Table where x.Contains("2008") select x
如果 stoptime 数据类型是字符串,您可以使用 .Contains() 函数,也可以使用 .StartsWith() 和 .EndsWith()。
如果您使用 contains to 方法,那么您正在执行 LIKE '%somestring%'。如果您使用startswith 方法,那么它与'somestring%' 相同。最后,endswith 与使用 '%somestring' 相同。
总而言之,包含将在字符串中找到任何模式,但开始和结束将帮助您在单词的开头和结尾找到匹配项。
真正有趣的一点是,当您使用“from x in context.Table where x.Contains("test") select x” 时,.NET 会创建诸如“Select * from table where name like '%test%'”之类的查询,即相当令人印象深刻
谢谢 - 很好的答案。
这实际上是一个 DateTime 类型;我不得不将“stoptime”类型转换为:
var query = from p in dbTransSummary.Transaction_Logs
where ( (DateTime) p.StopTime).Year == dtRollUpDate.Year
select
小点。效果很好!