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

标签 c# linq entity-framework sqlite

我已经使用过几次 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/

相关文章:

c# - GroupBy 键值对列表,然后重新组合结果

.net - 当我从未将实体添加到上下文时, Entity Framework 错误地保存了实体

c# - Metro 应用程序的富文本编辑器

c# - 将字符串拆分为一定大小的 block

Linq 到 Sql 多对多

c# - 获取 asp.net 样板存储库使用的 DbContext 实例

c# - 运行修改我的实体的存储过程后,我的 DbContext 会发生什么情况?

c# - 寻找在 Docx -> Pdf 转换服务中使用的 Pdf 打印机

c# - 将字节数组从 C++ 传递到 C# 程序集有哪些不同的方法?

c# - 将两个 LINQ 表达式合并为一个