简体   繁体   English

Linq效率-如何最好地在数据库中查询值列表?

[英]Linq efficiency - How do I best query a database for a list of values?

Let us say I have a database of Terms and a list of strings, is this a good (efficient) idea? 假设我有一个术语数据库和一个字符串列表,这是一个好主意吗? It works smoothly, but I'm not sure it is scalable or the most efficient. 它可以正常运行,但是我不确定它是否可扩展或最高效。

var results =
            from t in Terms
            join x in Targets on t.Term equals x
            select t;

Here Terms is a database table with index table Term. 这里的术语是带有索引表Term的数据库表。 Targets is an IEnumerable of strings. 目标是字符串的IEnumerable。 Terms might hold millions, Targets between 10-20 strings. 术语可能包含数百万个,目标介于10到20个字符串之间。 Any thoughts? 有什么想法吗?

Ultimately what matters, as far as efficiency is concerned, is if the query that is executed against the database is efficient. 最终,就效率而言,最重要的是针对数据库执行的查询是否有效。 To see this, you can either use SQL Profiler or find an application that will show you SQL generated by linq-to-sql. 为此,您可以使用SQL事件探查器,也可以找到一个应用程序来显示linq-to-sql生成的SQL。

If you use SQL Profiler, be sure to have it look for stored procedures, as Linq-to-sql uses the exec_sql procedure to execute queries. 如果使用SQL Profiler,请确保它查找存储过程,因为Linq-to-sql使用exec_sql过程执行查询。

If you need to join two tables on one key, as in your example, there's no other way to express it than an actual join. 如您的示例所示,如果您需要在一个键上连接两个表,那么除了实际的连接外,没有其他方法可以表达它。 What you have is as efficient as it CAN get. 您所拥有的就是它所能达到的最高效率。

However, change the select to return only the fields you're interested in, and make sure you trim them, because sql databases like to return char fields with trailing spaces, and they take time to process and transfer across the network. 但是,将select更改为仅返回您感兴趣的字段,并确保对它们进行修剪,因为sql数据库喜欢返回带有尾部空格的char字段,并且它们需要时间来处理和在网络上传输。

Hmm, I didn't know you could join a local collection in like that. 嗯,我不知道您可以加入本地收藏。 Perhaps that's a .Net 4.0 feature? 也许那是.Net 4.0功能?

I have frequently issued queries like this: 我经常发出这样的查询:

IQueryable<Term> query =
  from t in Terms 
  where Targets.Contains(t.Term)
  select t; 

There's a few caveats. 有一些警告。

  • The variable x must be a List<string> reference. 变量x必须是List<string>引用。 The variable x may not be an IList<string> reference. 变量x可能不是IList<string>引用。

  • Each string in the list is translated into a sql parameter. 列表中的每个字符串都转换为sql参数。 While linq to sql will happily translate many thousands of strings into parameters (I've seen 50k parameters), Sql Server will only accept ~2100. 虽然linq to sql会很乐意将成千上万个字符串转换为参数(我见过50k个参数),但Sql Server只接受〜2100。 If you exceed this limit, you'll get a sql exception. 如果超出此限制,则会出现sql异常。

  • nvarchar vs varchar indexes . nvarchar与varchar索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM