none
hi how solve this error "ExceptionMessage": "The entity or complex type 'WebApiStandAloneProject.Models.Student' cannot be constructed in a LINQ to Entities query.", RRS feed

  • Question

  • public IHttpActionResult GetAllStudent(bool includeAddress = false)
          {
              
              var studentList = _context.Students.Include(c => c.Address).Select(m => new Student()
              {
                  Id = m.Id,
                  FirstName = m.FirstName,
                  LastName = m.LastName,
                  Address = m.Address == null || includeAddress == false
                         ? null
                         : new Address()
                         {
                             StudentId = m.Id,
                             Address1 = m.Address.Address1,
                             Address2 = m.Address.Address2
     
                         }
     
     
              }).ToList<Student>();
     
     
              if (!_context.Students.Any())
              {
                  return NotFound();
              }
              return Ok(studentList);
     
          }
    Monday, October 23, 2017 2:55 AM

All replies

  • Select(m => new 
              {
                  Id = m.Id,
                  FirstName = m.FirstName,
                  LastName = m.LastName,
                  Address = m.Address == null || includeAddress == false
                         ? null
                         : new 
                         {
                             StudentId = m.Id,
                             Address1 = m.Address.Address1,
                             Address2 = m.Address.Address2
     
                         }
     
     
           
    Remove new of Student and Address in linq expression. Linq cannot new known entity but only anonymous ones.
    • Edited by Ryon Cui Monday, October 23, 2017 9:44 AM
    Monday, October 23, 2017 9:42 AM