LINQ GroupBy抛出错误

时间:2013-03-04 15:47:22

标签: c# linq join lambda linq-to-entities

 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();

嗨,我上面的查询加入了几个表,一切正常。然后我意识到一些外键可能是空的。

我已经研究了GroupByDefaultIfEmpty的用法,他们听起来很有希望所以我尝试将第一个Join更改为GroupJoin,但这引发了错误:

 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?)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

mGroup行中的

(device, mGroup) => new { device, mGroup.Name }实际上代表整个集合。您需要在其上执行Select

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

查看GroupJoin上的MSDN页面了解更多信息。