DavidB
DavidB

Reputation: 2596

LINQ GroupBy throwing errors

 var devSum = repository.Devices
                    .Where(dev => dev.Id == deviceId)
                    .Join(repository.ManagementGroups, device => device.ManagementGroupId, mGroup => mGroup.Id, (device, mGroup) => new { device, mGroup.Name })
                    .Join(repository.DataGroups, device_mGroup => device_mGroup.device.DataGroupId, dGroup => dGroup.Id, (device_mGroup, dGroup) => new { device_mGroup.device, managerName = device_mGroup.Name, dataName = dGroup.Name })
                    .Join(repository.DeviceTypes, d => d.device.TypeId, t => t.Id, (d, t) => new { d.device, d.dataName, d.managerName, TypeName = t.Name })
                    .SingleOrDefault();

Hi, I have the above query joining several tables and all was working. Then I realised some of the foreign keys may be empty.

I've researched the use of GroupBy and DefaultIfEmpty, and they sounded promising so I tried changing the first Join to GroupJoin on but this threw an error:

 var devSum = repository.Devices
                    .Where(dev => dev.Id == deviceId)
                    .GroupJoin(repository.ManagementGroups, device => device.ManagementGroupId, mGroup => mGroup.Id, (device, mGroup) => new { device, mGroup.Name })
                    .Join(repository.DataGroups, device_mGroup => device_mGroup.device.DataGroupId, dGroup => dGroup.Id, (device_mGroup, dGroup) => new { device_mGroup.device, managerName = device_mGroup.Name, dataName = dGroup.Name })
                    .Join(repository.DeviceTypes, d => d.device.TypeId, t => t.Id, (d, t) => new { d.device, d.dataName, d.managerName, TypeName = t.Name })
                    .SingleOrDefault();

'AnonymousType#1' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'AnonymousType#1' could be found (are you missing a using directive or an assembly reference?)

Can anyone help please?

Upvotes: 3

Views: 225

Answers (1)

Corey Adler
Corey Adler

Reputation: 16149

mGroup in the line (device, mGroup) => new { device, mGroup.Name } actually represents the whole collection. You'd need to do a Select on it:

(device, mGroup) => new { Device = device, NameGroup = mGroup.Select(m => m.Name) }

Check out the MSDN page on GroupJoin for more info.

Upvotes: 3

Related Questions