编辑:我需要帮助将这些 linq 查询重写为 SQL 查询以获得尽可能高的性能。
我有一张大约有 1000 万行的表。它由 7 列组成,包括 Id。首先是 Id,然后是“TradeObjectModel”的三个键,最后是保持不同 TradeObjectModels 评级值的三个整数。像这样:
当用户,例如 To1Id (TradeObjectModel1 所有者) 使用键 71 处理她对其他贸易对象的评级时,只有一行足以满足当前视图。
我解决这个问题的尝试看起来像这样(代码示例下面的解释):
IEnumerable<RatingListTriangleModel> allTriangleModels1 =
this._ratingListTriangleRepository.All.Where(
ratingListRow =>
ratingListRow.To1Id == myTradeObject.TradeObjectId);
var filteredallTriangleModels1 = from row in allTriangleModels1
group row by row.To2Id into g
select g.First();
IEnumerable<RatingListTriangleModel> allTriangleModels2 =
this._ratingListTriangleRepository.All.Where(
ratingListRow =>
ratingListRow.To2Id == myTradeObject.TradeObjectId);
var filteredallTriangleModels2 = from row in allTriangleModels2
group row by row.To3Id into g
select g.First().
IEnumerable<RatingListTriangleModel> allTriangleModels3 =
this._ratingListTriangleRepository.All.Where(
ratingListRow =>
ratingListRow.To3Id == myTradeObject.TradeObjectId);
var filteredallTriangleModels3 = from row in allTriangleModels3
group row by row.To1Id into g
select g.First();
var fileredallTriangleModels =
filteredallTriangleModels1.Union(filteredallTriangleModels2).Union(filteredallTriangleModels3).ToList();
ViewBag.TriangleCount = fileredallTriangleModels.Count();
foreach (var ratingListRow in fileredallTriangleModels)
{
//Find which one is my ad and set me as setter and their object as receiver
if (ratingListRow.To1Id == customer.TradeObjectId)
{
var ri = new TriangleViewModel(
customer.TradeObjectId,
this._customerRepository.FindTradeObjectId(ratingListRow.To2Id),
ratingListRow,
this._tradeobjectRepository.Find(ratingListRow.To2Id));
model.Models3.Add(ri);
continue;
}
if (ratingListRow.To2Id == customer.TradeObjectId)
{
var ri = new TriangleViewModel(
customer.TradeObjectId,
this._customerRepository.FindTradeObjectId(ratingListRow.To3Id),
ratingListRow,
this._tradeobjectRepository.Find(ratingListRow.To3Id));
model.Models3.Add(ri);
continue;
}
if (ratingListRow.To3Id == customer.TradeObjectId)
{
var ri = new TriangleViewModel(
customer.TradeObjectId,
this._customerRepository.FindTradeObjectId(ratingListRow.To1Id),
ratingListRow,
this._tradeobjectRepository.Find(ratingListRow.To1Id));
model.Models3.Add(ri);
}
}
首先,我得到我的对象在第一列的所有行,将它们分组以仅选择一个,然后在第二列和第三列继续对我做同样的事情。这里的 ToList() 只是临时的,让 med 能够在它们上运行秒表,每个都需要 0-12 秒。然后我加入他们并运行所有这些以在前端代码中创建 webgrid 使用的模型。
这会导致两个问题: 1. 需要很长时间。和 2. 如果我的贸易对象 ID 位于不止一列,我将获得不止一行,显示不止一个我感兴趣的贸易对象。