[英]How to join a table to itself in EF core?
我有一個表(“ProductParameter”)將兩個表鏈接在一起(“Product”和“Parameter”)它有字段Id,ProductId,ParameterId,Value,每個ParameterId都有一個[Value]我需要先過濾集合在逐個過濾ParameterId(其中pp.ParameterId = 4)之后,通過兩個ParameterId(其中pp.ParameterId = 4或pp1.ParameterId = 2和pp1.Value ='Standard')。
例:
+---------+-------------+------------+---------+
| ID | ProductId |ParameterId | Value |
+---------+-------------+------------+---------+
| 25 | 14 | 2 | Standard|
| 26 | 14 | 3 | CK45 |
| 27 | 14 | 4 | 63 |
| 28 | 15 | 2 | XXX |
| 29 | 15 | 3 | CK45 |
| 30 | 15 | 4 | 70 |
| 34 | 17 | 2 | Standard|
| 35 | 17 | 3 | CK45 |
| 36 | 17 | 4 | 40 |
| 37 | 25 | 2 | Standard|
| 38 | 25 | 3 | CK45 |
| 39 | 25 | 4 | 20 |
+---------+-------------+------------+---------+-
應該返回:
+-------+
| Value |
+-------+
| 63 |
| 40 |
| 20 |
+-------+
查詢的邏輯如下:
select distinct pp.Value from ProductParameters pp
join ProductParameters pp1 on pp1.ProductId = pp.ProductId and
pp1.ParameterId = 2 and pp1.Value = 'Standard'
where pp.ParameterId = 4
這是我在EF核心中的查詢:
public async Task<IEnumerable<ProductParameter>> GetProductDiameters(long id, string param = "Standard")
{
var value = await _context.ProductParameters
.Include(p => p.Product)
.ThenInclude(p => p.ProductParameters.Where(i => i.Value == param))
.Where(p => p.ParameterId == id)
.Distinct()
.ToListAsync();
return value;
}
拋出異常:
ArgumentException:ThenInclude屬性lambda表達式'p => {來自p.ProductParameters中的ProductParameter i,其中([i] .Value == __param_0)select [i]}'無效。 表達式應表示屬性訪問:'t => t.MyProperty'。 要定位在派生類型上聲明的導航,請指定目標類型的顯式類型lambda參數,例如'(派生d)=> d.MyProperty'。
哪里出錯了?
EF抱怨因為你試圖在里面過濾 。 ThenInclude(..)
語句。
var value = await _context.ProductParameters
.Include(p => p.Product)
.ThenInclude(p => p.ProductParameters.Where(i => i.Value == param)) //<-- here
.Where(p => p.ParameterId == id)
.Distinct()
.ToListAsync();
這是一個問題,因為EF將使用其中的函數來確定應該急切加載的表 。 Include(..)
和ThenInclude(..)
這些函數應該總是指向一個相關的表, 沒有別的 :)
正確的查詢方式如下:
var value = await _context.ProductParameters
.Include(p => p.Product)
.ThenInclude(p => p.ProductParameters) // <- removed the Where clause from here
.Where(p => p.ParameterId == id)
.Where(p => p.ProductParameters.Value == param)) //<- and added it here
.Distinct()
.ToListAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.