Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: The entity or complex type cannot be constructed in a LINQ to Entities query

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>
<% } %>
like image 237
Tsarl Avatar asked Aug 27 '11 15:08

Tsarl


2 Answers

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
};
like image 53
Steven Avatar answered Jan 02 '23 21:01

Steven


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.

like image 35
Magnus Avatar answered Jan 02 '23 19:01

Magnus