evi*_*red 2 c# linq lambda linq-to-sql
我知道Linq-to-SQL已经死了,但无论如何,我认为这是非常基本的,我只是对Linq-to-SQL对它生成的SQL做什么和不做什么感到困惑.
如果我已经将表达式树构建为"myPredicate",并且具有以下内容:
(from request in DataContext.RequestsTable
select request).Where(myPredicate)
.OrderByDescending(item => item.changeDate)
.Take(10)
Run Code Online (Sandbox Code Playgroud)
它会像下面的SQL一样工作:
SELECT TOP 10 * FROM RequestsTable
WHERE (<<myPredicate equivalent>>)
ORDER BY ChangeDate DESC
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很奇怪,因为".Where()"出现在我的示例代码中的"select"之后."select"和"where()"和"orderby()"的相对位置会影响事物吗?
或者,我可以用sql-esque语法完成所有操作吗?例如,有没有办法在替代语法中使用我的WHERE谓词,这样的话?
(from request in DataContext.RequestsTable
where [somehow inject myPredicate]
order by changeDate descending
select request).Take(10)
Run Code Online (Sandbox Code Playgroud)
你有相同的查询,LINQ to SQL将不会评估并生成T-SQL,直到你完成了一些事情来执行查询(例如.ToList()).顺序无关紧要.
实际上,您甚至可以在分配初始查询后添加OrderBy和Where子句.
例如
var query = (from x in context.RequestsTable
select x);
query = query.AsQueryable().Where(<>);
return query.ToList(); //executes
Run Code Online (Sandbox Code Playgroud)
是相同的:
return (from x in context.RequestsTable
where <>
select x).ToList(); //executes
Run Code Online (Sandbox Code Playgroud)
是相同的:
return (from x in context.RequestsTable
selext x).Where(<>).ToList();
Run Code Online (Sandbox Code Playgroud)
我不确定LINQ to SQL是"死的"但是我听说它可能会被卷入ADO实体框架.LINQ to SQL生成的T-SQL远远优于实体框架!