尝试将具有JOIN的记录排除到另一个对象时出错

时间:2012-03-29 08:05:15

标签: linq

在我的下面的代码中,有什么方法可以使用对象'WasteRecordsExcluded'中的结果与searchResults一起加入,基本上排除了我不想要的WasteId。

如果我调试到最后一行,我会收到错误:

base {System.SystemException} = {“查询包含对在不同数据上下文中定义的项目的引用。”}

或者,如果加入是不可能的,那么我可以将bHazardous从TRUE更改为FALSE,将FALSE更改为TRUE并进行某种“NOT IN”比较。

用这个去香蕉,有人帮忙吗?亲切的问候:

    var allWaste = _securityRepository.FindAllWaste(userId, SystemType.W);
    var allWasteIndicatorItems = _securityRepository.FindAllWasteIndicatorItems();

    // First get all WASTE RECORDS
    var searchResults = (from s in allWaste
                         join x in allWasteIndicatorItems on s.WasteId equals x.WasteId
                         where (s.Description.Contains(searchText)
                         && s.Site.SiteDescription.EndsWith(searchTextSite)
                         && (s.CollectedDate >= startDate && s.CollectedDate <= endDate))
                         && x.EWC.EndsWith(searchTextEWC)
                         select s).Distinct();

    var results = searchResults;



    if (hazardous != "-1")
    {
        // User has requested to filter on Hazardous or Non Hazardous only rather than Show All
        var WasteRecordsExcluded = (from we in _db.WasteIndicatorItems
        .Join(_db.WasteIndicators, wii => wii.WasteIndicatorId, wi => wi.WasteIndicatorId, (wii, wi) => new { wasteid = wii.WasteId, wasteindicatorid = wii.WasteIndicatorId, hazardtypeid = wi.HazardTypeId })
        .Join(_db.HazardTypes, w => w.hazardtypeid, h => h.HazardTypeId, (w, h) => new { wasteid = w.wasteid, hazardous = h.Hazardous })
        .GroupBy(g => new { g.wasteid, g.hazardous })
        .Where(g => g.Key.hazardous == bHazardous && g.Count() >= 1)
          select we);

        // Now join the 2 object to eliminate all the keys that do not apply
        results = results.Where(n => WasteRecordsExcluded.All(t2 => n.WasteId == t2.Key.wasteid));
    }


    return results;

1 个答案:

答案 0 :(得分:0)

也许是这样的:

.....
var results = searchResults.ToList();
.....
.....
.Where(g => g.Key.hazardous == bHazardous && g.Count() >= 1)
      select we).ToList();
.....