【问题标题】:Cannot compare elements of type. Only primitive types, enumeration types and entity types are supported无法比较类型的元素。仅支持原始类型、枚举类型和实体类型
【发布时间】:2015-01-16 10:43:27
【问题描述】:

我已经阅读了 herehere,但我仍然无法弄清楚为什么会出现此错误。 c.NvrId 和 n.Id 的类型都是int

var cameras = from c in context.CameraEntities
              join n in context.NetworkVideoRecorderEntities
                  on c.NvrId equals n.Id
                  into cn
              from x in cn.DefaultIfEmpty()
              where listofIds.Contains(c.Id)
              select new Camera
              {
                  Id = c.Id,
                  Name = c.Name,
                  NetworkVideoRecorder = cn == null ? null : new NetworkVideoRecorder
                  {
                      Id = x.Id,
                      Description = x.Description,
                      IP = x.IP,
                  }
              };

return cameras.ToList();

当我执行 cameras.ToList(); 时抛出错误

这是完整的错误信息:

Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1[[Models.NetworkVideoRecorderEntity, Asis.Ibss.Net.DataObjects, Version=2014.1.5494.33354, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported.

【问题讨论】:

  • 去掉cn == null ? null : 还能用吗?
  • 附带说明,我认为您应该检查x 是否为空,而不是cn
  • @RahulSingh ...好地方。

标签: c# .net linq entity-framework


【解决方案1】:

您在“选择”子句中进行了空检查。

NetworkVideoRecorder = cn == null ? null : new NetworkVideoRecorder { Id = x.Id, Description = x.Description, IP = x.IP, }

正如@RahulSingh 在 cmets 中指出的那样,我认为您最好检查 x 是否为空,而不是检查 cn 是否为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2014-11-16
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多