如果外键为null,则在linq查询中使用导航属性会引发错误

时间:2013-03-07 10:40:27

标签: c# linq linq-to-entities

 var devSum = repository.Devices
            .Where(dev => dev.Id == deviceId)
            .SingleOrDefault();
        vmDeviceSummary result = new vmDeviceSummary
        {
          DeviceId = deviceId,

          DeviceName = devSum.Name,
          MacAddress = devSum.MacAddress,
          DeviceType = devSum.DeviceType.Name,
          Enabled = devSum.Enabled.ToString(),
          ConfigurationLoaded = devSum.ConfigurationLoaded.ToString(),
          AllowReload = devSum.AllowDataReload.ToString(),
          DataGroup = devSum.DataGroup.Name,
          ManagementGroup = devSum.ManagementGroup.Name,
        };

我认为这应该可行,但如果在datagoups或managementGroup实体的链接中的外键中存在null,则会引发错误。

我如何解决这个问题,以便它像外部联接一样返回null?

3 个答案:

答案 0 :(得分:1)

它可能会有点难看,但你可以用三元运算符来做到这一点:

DeviceType = devSum.DeviceType != null ? devSum.DeviceType.Name : null,

答案 1 :(得分:0)

使用此

更改上述代码
var devSum = repository.Devices .Where(dev => dev.Id == deviceId) .FirstOrDefault();

答案 2 :(得分:0)

您可能需要执行Include

var devSum = repository.Devices
            .Include("DeviceType")
            .Include("ManagementGroup")
            .Where(dev => dev.Id == deviceId)
            .SingleOrDefault();