列表需要时间从数据库中插入数据

List take time to insert data from database

我有 class 的列表,其中 class 有 3 个这样的属性。

public string attributeName { get; set; }
public string strFormId { get; set; }
public string strValue { get; set; }

我正在通过这样的列表将我的数据库数据添加到其中

List<myAttributeData> attributesData = new List<myAttributeData>();
var result = db.ExecuteQuery<myAttributeData>(query, new object[0]);

// attributesData.Clear();
foreach (myAttributeData item in result.ToList())
{
    if (item.attributeName == "Province ")
    {
        var Loc = from d in db.tblLocations 
                  where d.LocationId == Convert.ToInt32(item.strValue)
                  select new
                  {
                       d.LocationName
                  };
        foreach (var item1 in Loc.ToList())
        {
            attributesData.Add(new myAttributeData()
            {
                attributeName = item.attributeName,
                strFormId = item.strFormId,
                strValue = item1.LocationName
            });
         }
     }

问题是现在我的数据库中有 7 万条记录 table 花费了太多时间,这需要半个多小时 关于这种情况的任何建议谢谢。我必须将我的数据添加到列表中,因为我需要它在需要时使用它,任何人都可以给我解决方案来减少将数据添加到字符串中的时间。

一个字:缓存。

此代码的问题在于您要遍历 70,000 条记录,对于每条记录,您都将返回数据库以读取额外信息。

foreach (myAttributeData item in result.ToList())
{
    if (item.attributeName == "Province ")
    {
        var Loc = from d in db.tblLocations  
        where d.LocationId == Convert.ToInt32(item.strValue)

如果您可以缓存位置列表(在调用 foreach 循环之前),您会发现您的代码运行良好

List<Location> cachedLocations = db.tblLocations.ToList();

..然后从那里设置您的 Loc 变量:

var Loc = from d in cachedLocations  
where d.LocationId == Convert.ToInt32(item.strValue)

始终将对数据库的调用次数保持在尽可能低的水平。

祝你好运!