gpt4 book ai didi

c# - Linq 查询和 Foreach 对来自 SQL 数据库的大量记录

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

我正在使用 Entity Framework 和 Linq。我需要查询对象的 2 个属性。

我在数据库中有这个对象(大约 200.000 条记录):

public class DeviceState
{
public int ID { get; set; }
public DateTime TimeStamp { get; set; }
public string StatusCode { get; set; }
public int Device_ID { get; set; }
}

我需要做这样的查询:

List<DeviceState> listState = systemDB.DeviceStates.Where(s => s.Device_ID == DeviceID).Where(l => l.TimeStamp > startDate).Where(l => l.TimeStamp < endDate).Where(s => s.StatusCode == "xx").ToList();
foreach (DeviceState status in listState)
{
// here I need to save in an object the status code and the time stamp:
object.StatusCode= status.StatusCode;
object.TimeStamp = status.TimeStamp;
}

此查询需要很长时间(大约 15 分钟)。我认为这是由于列表的创建。所以我尝试了这个:

foreach (DeviceState status in systemDB.DeviceStates.Where(s => s.Device_ID == DeviceID).Where(l => l.TimeStamp > startDate).Where(l => l.TimeStamp < endDate).Where(s => s.StatusCode == "xx"))
{
// here I need to save in an object the status code and the time stamp:
object.StatusCode= status.StatusCode;
object.TimeStamp = status.TimeStamp;
}

创建列表的速度要快得多。但由于 foreach 循环,我仍然遇到性能问题。每个元素需要 5ms。

我需要找到一个只需几秒钟即可执行的解决方案。

最佳答案

您可以执行这些操作来帮助生成查询。

  1. 只返回您需要的。现在您要返回所有内容,但您只使用过 TimeStamp,所以只需返回即可。您正在下面设置 StatusCode,但是您已经在 Where 子句中过滤了它,因此您知道所有返回的项目都有一个 StatusCode 为“xx”,因此也不需要检索它。这意味着通过网络返回的数据更少,将数据映射到对象所需的周期更少,数据占用的内存也更少。
  2. 您应该查看 EF 生成的查询。您可以使用 sql profiler 工具(Sql Server 有一个名为 Sql Profiler 的工具)来执行此操作。然后查看查询计划,看看是否有任何可以使您受益的东西,例如添加缺失索引。此分析应在数据库服务器上完成,而不是在 C# 中。
  3. 合并您的 where 子句,因为它更易于阅读。

代码

// list of timestamps from database
var timeStamps = systemDB.DeviceStates.Where(s => s.Device_ID == DeviceID &&
s.TimeStamp > startDate &&
s.TimeStamp < endDate &&
s.StatusCode == "xx")
.Select(x => x.TimeStamp).ToList();

如果你仍然想要你的状态代码,因为你删除了过滤器,你可以这样做

var timeStamps = systemDB.DeviceStates.Where(s => s.Device_ID == DeviceID &&
s.TimeStamp > startDate &&
s.TimeStamp < endDate &&
s.StatusCode == "xx")
.Select(x => new {x.TimeStamp, x.StatusCode})
.ToList();

关于c# - Linq 查询和 Foreach 对来自 SQL 数据库的大量记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915516/

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