Error: object or complex type cannot be constructed in LINQ to Entities query

I get this error "System.NotSupportedException: object or complex type" MyModel.Team "cannot be constructed in a LINQ to Entities query." when I go to the Team / Index / {id} page. Can someone point me to the error I requested?

Controller:

public ActionResult Index(int id) { IQueryable<Team> teams = teamRepository.GetTeamByPersonID(id); return View("Index", teams); } 

Repository:

 public IQueryable<Team> GetTeamByPersonID(int id) { return from t in entities.Teams join d in entities.Departments on t.TeamID equals d.TeamID where (from p in entities.Person_Departments join dep in entities.Departments on p.DepartmentID equals dep.DepartmentID where p.PersonID == id select dep.TeamID).Contains(d.TeamID) select new Team { TeamID = t.TeamID, FullName = t.FullName, ShortName = t.ShortName, Iso5 = t.Iso5, DateEstablished = t.DateEstablished, City = t.City, CountryID = t.CountryID }; } 

ViewModel:

 public IQueryable<Team> teamList { get; set; } public TeamViewModel(IQueryable<Team> teams) { teamList = teams; } 

View:

 <% foreach (var team in Model){ %> <tr> <td><%: Html.ActionLink(team.ShortName, "Details", new { id=team.TeamID}) %></td> <td><%: team.City %></td> <td><%: team.Country %></td> </tr> <% } %> 
+6
source share
2 answers

The problem is that you create the Team class in the select statement, which is not supported by LINQ to SQL. Change select to:

 select t 

or use an anonymous type:

 select new { TeamID = t.TeamID, FullName = t.FullName, ShortName = t.ShortName, Iso5 = t.Iso5, DateEstablished = t.DateEstablished, City = t.City, CountryID = t.CountryID }; 

or use DTO (anything that is not an entity):

 select new TeamDTO { TeamID = t.TeamID, FullName = t.FullName, ShortName = t.ShortName, Iso5 = t.Iso5, DateEstablished = t.DateEstablished, City = t.City, CountryID = t.CountryID }; 
+10
source

If the Team class is Entity, it cannot be created inside the linq statement. You should consider creating your own class and returning it instead. Or maybe just select t .

+4
source

Source: https://habr.com/ru/post/896041/


All Articles