日期:2014-05-20  浏览次数:20769 次

LinQ To SQL 多层表大量数据关联的问题
我现在有三张表:
表DeviceInfo 为主表,数据量 1000左右,
表DeviceParameter 为 DeviceInfo 的从表,数据量3万左右,
表DeviceParameterProperty 为 DeviceParameter 的从表,数据量30万左右。
因为系统初始化时,需要把三张表按当前的关系,一次性查出来,试过直接查,半小时都没出结果。
把数据拿到客户端来,然后手工组合,跑了10分钟还没出结果。

注:EntifyFramwork可以在10秒内完成,但当前的代码都是Linq to SQL,暂不想增加工作量。

本地组合用代码如下:
C# code

RefreshLinQDataContext dataContext = new RefreshLinQDataContext();
dataContext.DeferredLoadingEnabled = false;//防止foreach时到数据库做增量检查
var _DeviceInfo = dataContext.DeviceInfo.Where(v => v.Stauts == 2).OrderBy(v => v.InfoID).ToList();
var _DeviceParam = dataContext.DeviceParameter.ToList().GroupBy(v => v.InfoID).AsParallel().OrderBy(v => v.Key);
var _DeviceParamProperty = dataContext.DeviceParameterProperty.ToList().GroupBy(v => v.DeviceParamID).AsParallel().OrderBy(v => v.Key);
//到这里用了2秒左右
foreach (var di in _DeviceInfo)
{
    di.DeviceParameter.AddRange(_DeviceParam.Single(v => v.Key == di.InfoID));
    var dsfs = _DeviecSafeTime.SingleOrDefault(v => v.Key == di.InfoID);
    foreach (var dp in di.DeviceParameter)
    {                    
         dp.DeviceParameterProperty.AddRange(_DeviceParamProperty.Single(v => v.Key == dp.DeviceParamID));
    }
}

我觉得是在AddRange时不停的开辟内存所致。
还请高手们帮忙解决下,谢谢。

------解决方案--------------------
AddRange添加一个IEnumerable<T>
Single 是返回一个T 

你的 不报错?
di.DeviceParameter.AddRange(_DeviceParam.Single(v => v.Key == di.InfoID));


------解决方案--------------------
.ToList() GroupBy 这些都是非延迟查询操作符
破坏了LINQ2SQL的延迟查询的特性
------解决方案--------------------
断点跟一下