我有 3 張桌子:
合同、事項和索賠。每個表與下表具有 1:N 的關系。
我想選擇合同 con_name = 'C109K' 的索賠名稱
var claims = await _context.Claims.AsNoTracking()
.Include(cl=>cl.Matter)
.ThenInclude(mat=>mat.Contract)
.Where(con=>con.con_name=='C109K')
.Select(cl=>new{name=cl.cl_name})
錯誤是 where 子句無法找到 con_name 因為背景關系是宣告。
我也嘗試了另一種方式 - 即 - 從合同開始查詢。但在這種情況下,選擇無法獲取宣告名稱,因為查詢背景關系是合同。
如何正確撰寫此查詢?
uj5u.com熱心網友回復:
沒有模型很難確定,但我認為這應該可行:
var claims = await _context.Claims.AsNoTracking()
.Include(cl=>cl.Matter)
.ThenInclude(mat=>mat.Contract)
.Where(cl=>cl.Matter.Contract.con_name=='C109K') // <-- find the contract associated with the claim
.Select(cl=>new{name=cl.cl_name})
該.Include()和.ThenInclude()方法用于加載相關物體(見檔案預先加載)。他們要求 EF Core 從資料庫中檢索資料,并將其加載到關聯的物體中。
例如在你的情況下:
var claim = (await _context.Claims.AsNoTracking()).First();
var matter = claim.Matter; // matter will always be null, because it was no loaded
claim = (await _context.Claims.Include(cl=>cl.Matter).AsNoTracking()).First();
matter = claim.Matter; // the claim's matter is loaded thanks to the Include call
var contract = matter.Contract; // contract is null because it was not loaded
claim = (await _context.Claims.Include(cl=>cl.Matter).ThenInclude(mat=>mat.Contract).AsNoTracking()).First();
matter = claim.Matter; // the claim's matter is loaded thanks to the Include call
contract = matter.Contract; // contract is loaded thanks to the ThenInclude call
這些方法允許對從資料庫中檢索哪些資料進行精細控制:有時您不需要所有資料,只需要頂級視圖。
但是,在您的情況下,不需要這些呼叫,因為您不檢索鏈接的物體:您只需要它們進行過濾,并且過濾僅通過運行適當的 SQL 查詢來完成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/405927.html
標籤:
