无法比较类型&System; Series.Collections.Generic.ICollection`1'的元素。仅支持基本类型,枚举类型和实体类型

时间:2017-12-12 21:23:05

标签: c# linq icollection

执行以下代码时出错,是LINQ的新手,无法找到如何分配子对象" StudentAddresses"作为icollection类型的值到学生模型

navbar-expand-md

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-1)

我认为这可以帮到你

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

如果注释访问属性存在问题并再次测试它,请确定您在哪里遇到问题。谢谢