Как добиться объединения нескольких таблиц в Entity Framework с правильным ответом json - PullRequest
0 голосов
/ 06 января 2019

Я пытаюсь объединить 3 таблицы, используя оператор Entity Framework LINQ.

Это моя схема базы данных:

enter image description here

Данные в 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

Вот код 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

Как видите, он создает дополнительное количество узлов, которое совпадает с числом типов устройств!

Ответы [ 2 ]

0 голосов
/ 06 января 2019

Вот как я решил это с помощью AutoMapper

        var devicetypegroups = await _context.DeviceTypeGroups
                .Include(b => b.DeviceTypes)
                .Include(p => p.Peers)
                .ToListAsync();


        var model = _mapper.Map<IEnumerable<DeviceTypeGroupDto>>(devicetypegroups);

:)

0 голосов
/ 06 января 2019

Вы хотите что-то вроде ниже:

    var details = (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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...