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

南楼画角 提交于 2019-11-30 04:38:50

问题


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>
<% } %>

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7215354/error-the-entity-or-complex-type-cannot-be-constructed-in-a-linq-to-entities-qu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!