更新:此问题中涉及的两个查询都是正确的。原因是测试环境中的数据丢失。
我有三个桌子。
我的目标是返回每个用户特定的平衡单元及其说明列表。换句话说,第一部分是我想在“成本中心访问”表中检查用户可以访问哪些成本中心,并使用该成本中心根据其与成本中心的关联来过滤出“平衡”单元。
这部分很容易完成:
var bunits = from csa in _costCenterAccessRepo.GetAll()
join w in _worksheetRepo.GetAll() on csa.CostCenterID equals w.CostCenterID
where csa.EmplID == user.EmployeeID
select new { w.BalancingUnitID };
我遇到的问题是,当我添加另一个联接时,该联接使我可以获得上面每个BalancingUnitID的相应描述
我尝试了以下操作,但未返回任何结果:
var bunits = from csa in _costCenterAccessRepo.GetAll()
join w in _worksheetRepo.GetAll() on csa.CostCenterID equals w.CostCenterID
join b in _balancingUnitRepo.GetAll() on w.BalancingUnitID equals b.ID
where csa.EmplID == user.EmployeeID
select new { w.BalancingUnitID, b.Description };
我可以确认有数据要返回,并且第一个查询为我提供了正确的平衡单位,只是没有说明。
如何重写以上语句以完成结果?
答案 0 :(得分:0)
您在w
的联接在两个查询之间有所不同。
join w in _worksheetRepo.GetAll() on csa.CostCenterID equals w.CostCenterID
join w in _worksheetRepo.GetAll() on csa.CostCenterValue equals w.CostCenterID
从此伪数据开始:
public static class _costCenterAccessRepo
{
public static List<CostCenterAccess> GetAll() =>
new List<CostCenterAccess>()
{
new CostCenterAccess() { EmplID = 42, CostCenterID = 1 }
};
}
public class CostCenterAccess
{
public int EmplID;
public int CostCenterID;
}
public static class _worksheetRepo
{
public static List<Worksheet> GetAll() =>
new List<Worksheet>()
{
new Worksheet() { CostCenterID = 1, BalancingUnitID = 2 }
};
}
public class Worksheet
{
public int CostCenterID;
public int BalancingUnitID;
}
public static class _balancingUnitRepo
{
public static List<BalancingUnit> GetAll() =>
new List<BalancingUnit>()
{
new BalancingUnit() { ID = 2, Description = "Foo" }
};
}
public class BalancingUnit
{
public int ID;
public string Description;
}
public static class user
{
public static int EmployeeID = 42;
}
然后,当我同时运行两个查询时,它们就可以正常工作。
答案 1 :(得分:0)
您可以尝试以下操作:也许尝试左联接。
var bunits = from csa in _costCenterAccessRepo.GetAll()
join w in _worksheetRepo.GetAll() on csa.CostCenterID equals w.CostCenterID into csaw
from jts in csaw.DefaultIFEmpty()
join b in _balancingUnitRepo.GetAll() on jts.BalancingUnitID equals b.ID
where csa.EmplID == user.EmployeeID into anotherJoin
from values in anotherJoin.DefaultIfEmpty()
select new { jts.BalancingUnitID ?? 0, values.Description ?? String.Empty };