我想寫在這個產品表上的Linq查詢基於FacetTypes需要按他們的方面分組。Linq和EntityFramework 4與多個內部連接嵌套子查詢
這是表結構:
我獲得通過facetTypeIds的陣列,說9,6,52
FacetTypeId 9 has a name of "160" and is a Facet of "Size"
FacetTypeId 6 has a name of "157" and is a Facet of "Size"
FacetTypeId 52 has a name of "Cool Brand" and is a Facet of "Brand"
他們需要構建成聯接基礎上查詢面,像這樣:
select * from products p
inner join (select productId from productFacets where facetTypeId in (9, 6))
p1 on p1.productId = p.productId
inner join (select productId from productFacets where facetTypeId in (52))
p2 on p2.productId = p.productId
結果是一個結果集,上面寫着:
Get me產品有品牌「酷品牌」和尺寸(160或157)
我將如何去創建一個linq查詢,將動態構建這?
我有點卡在這將如何形成linq。
編輯:
這是代碼,我有點想出但是感覺非常低效。
MyDbContext _context;
// Groups FacetTypeIds by Facet into int lists
Dictionary<int, List<int>> createFacetGroup(int[] facetTypeIds)
{
var facets = new Dictionary<int, List<int>>();
var facetTypes = from ft in _context.FacetTypes where facetTypeIds.Contains(ft.FacetTypeId) select ft;
foreach (var facetType in facetTypes)
{
if (facets.ContainsKey(facetType.Facet.FacetId))
facets[facetType.Facet.FacetId].Add(facetType.FacetTypeId);
else
facets.Add(facetType.Facet.FacetId, new List<int> { facetType.FacetTypeId });
}
return facets;
}
public List<Product> FindProductsByGroupedFacetTypeIds(int[] facetTypeIds)
{
var groupedFacetTypeIds = createFacetGroup(facetTypeIds);
// this seem very inefficient but ToList needs to be called
// otherwise the results products in the foreach loop dont end
// up with the correct result set
var products = _context.Products.ToList();
foreach (var facetTypeIdGroup in groupedFacetTypeIds)
{
var facetTypeIdGroupArray = facetTypeIdGroup.Value.ToArray();
products = (from p in products where p.FacetTypes.Any(x => facetTypeIdGroupArray.Contains(x.FacetTypeId)) select p).ToList();
}
return products;
}
歡呼聲中,我得到了你的查詢一些調整後的工作,但我會如何動態地構建基於給定的facetTypeIds陣列上查詢? –
我想你想要2陣列嗎? 一個用於OR條件,另一個用於AND條件 或者一個用於SIZE,另一個用於品牌 是嗎? – AlaaL
該數組可以包含許多ID。所以會有一些不爲人知的方面,例如尺寸,品牌,顏色,形狀,重量等等 –