我想使用多对多连接检索LINQ中制造商的所有记录。
让我们考虑一下
表'项目':
id | name
----------
1 | A
---------
2 | B
--------
3 | C
--------
表'制造商':
ManufactuerId | Name
-------------------
1 | XYZ
-------------------
2 | ABC
--------------------
3 | ZZZ
----------------------
表'ManufacturerItem':
ManufacturerItemID | ManufacturerId | ItemId
-------------------------------------------
1 | 1 | 1
-------------------------------------------
2 | 1 | 2
-------------------------------------------
3 | 2 | 1
------------------------------------------
4 | 3 | 2
------------------------------------------
5 | 1 | 3
------------------------------------------
我想获取拥有我提供的所有商品的制造商的记录。 因此,如果输入{A,B},我想获得XYZ制造商的输出。
答案 0 :(得分:1)
var tableItems = new[] {
new { Id = 1, Name = "A" },
new { Id = 2, Name = "B" },
new { Id = 3, Name = "C" }
};
var tableManufacturer = new[] {
new { ManufacturerId = 1, Name = "XYZ" },
new { ManufacturerId = 2, Name = "ABC" },
new { ManufacturerId = 3, Name = "ZZZ" }
};
var tableManufacturerItem = new[]
{
new {ManufacturerItemID = 1, ManufacturerId = 1, ItemId = 1},
new {ManufacturerItemID = 2, ManufacturerId = 1, ItemId = 2},
new {ManufacturerItemID = 3, ManufacturerId = 2, ItemId = 1},
new {ManufacturerItemID = 4, ManufacturerId = 3, ItemId = 2},
new {ManufacturerItemID = 5, ManufacturerId = 1, ItemId = 3},
};
var itemsToSearch = new[] { "A", "B" };
var result = tableManufacturerItem
.GroupBy(x => x.ManufacturerId)
.Where(m => tableItems.Where(item => itemsToSearch.Contains(item.Name)).Select(x => x.Id)
.Except(m.Select(x => x.ItemId))
.Count() == 0)
.Select(x => tableManufacturer.First(m => m.ManufacturerId == x.Key))
.Select(m => m.Name)
.ToList();