简体   繁体   English

带有大型数据库表的LINQ to SQL可提高性能

[英]LINQ to SQL with a large database table increase performance

I am doing a search on a database table using a wildcard(The contains extension) Here is the code 我正在使用通配符对数据库表进行搜索( contains扩展名)这是代码

// This gets a list of the primary key IDs in a table that has 5000+ plus records in it
List<int> ids = context.Where(m => m.name.ToLower().Contains(searchTerm.ToLower())).Select(m => m.Id).ToList();


// Loop through all the ids and get the ones that match in a different table (So basically the FKs..)
foreach (int idin nameId)
{
    total.AddRange(context2.Where(x => x.NameID == id).Select(m => m.Id).ToList());
}

In there anything I could change in the LINQ that would result in getting the IDs faster? 我可以在LINQ中进行任何更改以导致更快地获取ID吗?

Thanks 谢谢

I have not tested it, but you could do something along these lines: 我尚未对其进行测试,但是您可以按照以下方式进行操作:

var total =
    from obj2 in context2
    join obj1 in context1 on obj2.NameID equals obj1.Id
    where obj1.name.ToLower().Contains(searchTerm.ToLower())
    select obj2.Id

It joins the two tables, performing a cartesian product first and then limiting it to the pairs where the NameId s match (see this tutorial on the join clause ). 它连接两个表,首先执行笛卡尔乘积,然后将其限制为NameId匹配的对(请参阅join子句中的本教程 )。 The where line does the actual filtering. where行进行实际过滤。

It should be faster because the whole matching is done in the database, and only the correct ids are returned. 它应该更快,因为整个匹配都在数据库中完成,并且仅返回正确的ID。

If you had a Name property in the context2 item class that holds a reference to the context1 item, you could write it more readable: 如果你有一个Name在属性context2保存到一个参考项类context1项目,你可以写它更易读:

var total = context2
    .Where(x => x.Name.name.ToLower().Contains(searchTerm.toLower()))
    .Select(x => x.ID);

In this case, Linq to SQL would do the join automatically for you. 在这种情况下,LINQ到SQL会做的join为你自动。

In terms of performance you can see tests that show if you search 1 string in 1 000 000 entries its around 100 ms. 在性能方面,您可以看到测试,显示是否在100万个条目中搜索1 000 000个条目中的1个字符串。

Here is the link with tests and implementation. 这是测试和实施的链接

for (int y = 0; y < sf.Length; y++)
    {
        c[y] += ss.Where(o => o.Contains(sf[y])).Count();
    }

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

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