I get this error "System.NotSupportedException: The entity or complex type 'MyModel.Team' cannot be constructed in a LINQ to Entities query." when I navigate to the Team/Index/{id} page. Can someone point me to the mistake I did please?
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>
<% } %>
The problem is that you are creating a Team
class in a select
statement, which is not supported by LINQ to SQL. Change your 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 a 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
};
If class Team
is an Entity it can not be created inside a linq statement. You should consider creating your own class and return that instead. Or maybe just select t
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With