4

我正在使用 EF4 查询 oracle 数据库。

我有 2 个表POINTS(大约 100 000 行)COUNTRIES,每个点都有一个countryCode作为外键

我在存储库中有以下 2 种方法

public List<PointsTable> GetAll()
{
    using (Entities context = new Entities())
    {
        List<PointsTable> theList = context.POINTS_TABLE.ToList();
        return theList;
    }
}

public List<PointsTable> GetAllComplete()
{
    using (Entities context = new Entities())
    {
        List<PointsTable> theList = context.POINTS_TABLE.Include("Countries").ToList();
        return theList;
    }
}

GetAll需要5秒,但需要GetAllComplete2分钟!

我有使用AsParallel(),但收益是荒谬的。

我可以加快速度,或者是什么导致它变慢?

4

2 回答 2

7

原因是,对于每条记录,您都在检索它的国家,其中 200k 记录乘以很多记录。

您是否打算稍后查询这些数据以将其减少到您的特定需求?如果是这样,请不要.ToList()他们。

更改您的存储库方法以返回IQueryable,这样您可以将查询限制为稍后需要的特定数据,从而减少您放入内存的数据量

private Entities _context;

public PointsRepository(Entities context)
{
    _context = context
}

public IQueryable<PointsTable> GetAll()
{
    return context.POINTS_TABLE;
}

public IQueryable<PointsTable> GetAllComplete()
{
    return context.POINTS_TABLE.Include("Countries");
}

然后,您可以添加您的特定过滤器和ToList较小的结果。例如

using (Entities context = new Entities())
{
    var rep = new PointsRepository(context);

    // This will change the query you send to sql to only 
    // retrieve the specific data you want and should result 
    // in much quicker execution
    var result = rep.GetAllComplete()                    // get all with includes
                    .Where(p => p.Property = "Specific") // refine the query 
                    .ToList()                            // retrieve the data and add to memory
}

希望这可以帮助

于 2013-10-30T10:40:22.877 回答
0

AS Parallel(),不适用于 Linq to Entities,仅适用于 Linq to Object。

用 EF 加载 200K 不是很好。

您可以使用只读负载提高性能:

context.POINTS_TABLE.MergeOption = MergeOption.NoTracking;
于 2013-10-30T10:25:34.450 回答