Я пытаюсь объединить 3 таблицы, используя оператор Entity Framework LINQ.
Это моя схема базы данных:
![enter image description here](https://i.stack.imgur.com/e5Xra.png)
Данные в DeviceTypeGroups
таблице:
Key | Name
------------+-------------------
111 GroupOne
112 GroupTwo
Данные в таблице DeviceTypes
:
Key | Name | DeviceTypeGroupKey
------------+--------------+--------------------
1 Type1 111
2 Type2 111
3 Type3 112
Данные в таблице Peers
:
Key | Name | DeviceTypeGroupKey
------------+--------------+---------------------
1 Peer1 111
2 Peer2 112
3 Peer3 112
Я хочу получить такой вывод:
![enter image description here](https://i.stack.imgur.com/e198e.png)
Вот код LINQ и метод веб-API C #, который я пытаюсь
[HttpGet]
[Route("devicetypegroups")]
[Produces("application/json")]
[SwaggerOperation("GetDeviceTypeGroups")]
[SwaggerResponse(400, "Bad input parameter")]
[SwaggerResponse(404, "Not found")]
[SwaggerResponse(500, "Internal server error")]
public virtual IActionResult GetDeviceTypeGroups()
{
try
{
var devicetypegroups =
(from dtg in _context.DeviceTypeGroups join dt in _context.DeviceTypes
on dtg.Key equals dt.DeviceTypeGroup.Key into dtgleft from dtgrecs in dtgleft.DefaultIfEmpty()
join pr in _context.Peers on dtgrecs.Key equals pr.DeviceTypeGroup.Key into peerleft
from peerleftRecs in peerleft.DefaultIfEmpty()
select new { dtg.Key, dtg.Name, dtg.DeviceTypes, dtg.Peers }).ToList();
}
}
Но он не возвращает правильный ответ, он добавляет несколько дополнительных записей:
![enter image description here](https://i.stack.imgur.com/oLs79.png)
Как видите, он создает дополнительное количество узлов, которое совпадает с числом типов устройств!