【发布时间】:2015-06-22 14:41:14
【问题描述】:
我已经使用了几次 MS SQL 服务器,但在使用 linq 到实体进行查询时还没有遇到速度问题。这一次,我使用 sqlite,将整个数据库与应用程序一起发送。
我有一个包含 4 个搜索字段的 winforms 应用程序。我的目标是设计搜索以使结果反映单个字段或多个字段(根据哪些字段具有搜索词构建查询)。
目前,我的查询有效,但需要相当长的时间才能针对 sqlite 数据库执行。特别是在第一次运行时。我认为这是因为 sqlite 背后没有强大的服务器,结果在本地处理并加载到内存中。我认为数据库正在为其自身编制索引,或者必须第一次构建某种缓存。
我如何优化我的 linq 查询以使我不必将整个表加载到内存中,然后限制结果,但在加载表时限制结果?
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();
}
}
我已将索引应用于数据库本身的这些字段,但我觉得问题出在我的查询中。关于重构优化的任何建议?
截至目前,数据库约有 35 万条记录,并且可能会变得更大。最终,我将停止向其中添加记录,但我们假设粗略估计它将有大约 70 万条记录
【问题讨论】:
标签: c# linq entity-framework sqlite