【问题标题】:Cannot compare elements of type 'System.Collections.Generic.ICollection`1'. Only primitive types, enumeration types and entity types are supported无法比较“System.Collections.Generic.ICollection`1”类型的元素。仅支持原始类型、枚举类型和实体类型
【发布时间】:2017-12-12 21:23:05
【问题描述】:

执行以下代码时出错,LINQ 新手,无法找到如何将子对象“StudentAddresses”值分配给学生模型中的 collection 类型

IList<StudentViewmodel> students = null;

using (var CTX = new StudentEntities())
{
    students = CTX.Students.Include("JP").Select(
        s => new StudentViewmodel()
        {
            Id = s.StudentId,
            FirstName = s.FirstName,
            LastName = s.LastName,
            address =  new AddressViewmodel()
            {
                // Address1 = s.StudentAddresses.Select(t => t.Address1).ToString()
                Address1 = s.StudentAddresses.OfType<AddressViewmodel>().FirstOrDefault().Address1.ToString()
            }
        }

        ).ToList<StudentViewmodel>();
}

【问题讨论】:

    标签: c# linq icollection


    【解决方案1】:

    我的问题已解决,这里是更新代码

            IList<StudentViewmodel> students = null;using (var CTX = new StudentEntities())
            {
                students = CTX.Students.Include("JP").Select(
                    s => new StudentViewmodel()
                    {
                        Id = s.StudentId,
                        FirstName = s.FirstName,
                        LastName = s.LastName,
                        address = new AddressViewmodel()
                        {
                           Address1 = s.StudentAddresses.FirstOrDefault().Address1 ,
                           Address2 = s.StudentAddresses.FirstOrDefault().Address2,
                           City = s.StudentAddresses.FirstOrDefault().City,
                           State = s.StudentAddresses.FirstOrDefault().State
                        }
                    }
    
                    ).ToList<StudentViewmodel>();
            }
    

    【讨论】:

      【解决方案2】:

      我认为这可以帮助你

      IList<StudentViewmodel> students = null;
      
      using (var CTX = new StudentEntities())
      {
          students = CTX.Students.Include("JP").ToList().Select(
              s => new StudentViewmodel()
              {
                  Id = s.StudentId,
                  FirstName = s.FirstName,
                  LastName = s.LastName,
                  address =  new AddressViewmodel()
                  {
                      // Address1 = s.StudentAddresses.ToList().Select(t => t.Address1).ToString()
                      Address1 = s.StudentAddresses.OfType<AddressViewmodel>().FirstOrDefault().Address1.ToString()
                  }
              }
      
              ).ToList<StudentViewmodel>();
      }
      

      如果评论访问属性有问题,再测试一次。确定你哪里有问题。谢谢

      【讨论】:

      • 评论地址属性并再次运行。如果有问题。再发消息。我改变答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2019-05-09
      • 2014-11-16
      • 1970-01-01
      相关资源
      最近更新 更多