[英]How to create a nested LINQ statement containing two joins
更新:此問題中涉及的兩個查詢都是正確的。 原因是測試環境中缺少數據。
我有三張桌子。
我的目標是返回一個平衡單元列表及其特定於每個用戶的描述。 換句話說,第一部分是我想檢查用戶可以在成本中心訪問表中訪問哪些成本中心,並使用它根據與成本中心的關聯來過濾掉平衡單位。
這部分很容易完成:
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 };
我可以確認有數據要返回並且第一個查詢為我提供了正確的平衡單位,只是沒有描述。
我怎樣才能重寫上面的語句來完成結果?
您對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;
}
然后,當我運行您的兩個查詢時,它們都可以正常工作。
您可以嘗試以下操作:也許嘗試左連接。
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 };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.