gpt4 book ai didi

c# - sqlite查询慢,如何优化(使用linq to entities)

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:33 25 4
gpt4 key购买 nike

我已经使用过几次 MS SQL 服务器,在使用 linq to entities 查询时还没有遇到速度问题。这一次,我使用 sqlite,将整个数据库与应用程序一起发送。

我有一个包含 4 个搜索字段的 winforms 应用程序。我的目标是以这样一种方式设计搜索,使结果反射(reflect)单个字段或多个字段(基于哪些字段具有搜索词来构建查询)。

目前,我的查询有效,但需要花费大量时间才能对 sqlite 数据库执行。特别是在第一次运行时。我认为这是因为 sqlite 背后没有强大的服务器,结果在本地处理并加载到内存中。我在想数据库正在为自己编制索引,或者必须在第一次建立某种缓存。

我如何优化我的 linq 查询到 sqilte,我不必将整个表加载到内存中然后限制结果但在加载表时限制结果?

    public List<ResultGridviewModel> GetChartsFromSearch(string patientID, string firstName, string lastName, DateTime? dateOfBirth)
{
using (var _dataContext = new dbEntities())
{

var records = (from c in _dataContext.charts
select new ResultGridviewModel
{
AltID = c.AltID,
FirstName = c.FirstName,
LastName = c.LastName,
DateOfBirth = c.DateOfBirth,
Description = c.Description,
ServiceDateTime = c.ServiceDateTime
});


// AltID (PatientID)
if (!string.IsNullOrEmpty(patientID))
{
records = records.Where(x => x.AltID.Contains(patientID.Trim().ToUpper()));
}

// First Name
if (!string.IsNullOrEmpty(firstName))
{
records = records.Where(x => x.FirstName.Contains(firstName.Trim().ToUpper()));
}

// Last Name
if (!string.IsNullOrEmpty(lastName))
{
records = records.Where(x => x.LastName.Contains(lastName.Trim().ToUpper()));
}

// Date Of Birth
if (dateOfBirth != null)
{
records = records.Where(x => x.DateOfBirth == dateOfBirth);
}


return records.ToList();
}
}

我已将索引应用于数据库本身的这些字段,但我觉得问题出在我的查询中。关于优化重构的任何建议?

截至目前,数据库大约有 350k 条记录,并且可能会变得更大。最终,我将停止向其中添加记录,但让我们假设粗略估计它将有 ~700k 条记录

最佳答案

最大的优化是将 Contains 更改为 StartsWith。这相当于从 name like '%search%' 更改为 name like 'search%'。否则 SQLite 无法完全使用您放置在列上的索引,您基本上是在搜索整个表。

// First Name
if (!string.IsNullOrEmpty(firstName))
{
firstName = firstName.Trim().ToUpper();
records = records.Where(x => x.FirstName.StartsWith(firstName));
}

关于c# - sqlite查询慢,如何优化(使用linq to entities),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com