错误:无法在LINQ to Entities查询中构造实体或复杂类型

时间:2011-08-27 15:04:53

标签: linq-to-sql asp.net-mvc-2

我收到此错误“System.NotSupportedException:无法在LINQ to Entities查询中构造实体或复杂类型'MyModel.Team'。”当我导航到Team / Index / {id}页面时。有人能指出我做的错误吗?

控制器:

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

存储库:

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

视图模型:

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

查看:

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

2 个答案:

答案 0 :(得分:10)

问题是您正在Team语句中创建select类,LINQ to SQL不支持该类。将您的select更改为:

select t

或使用匿名类型:

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

或使用DTO(任何不是实体的东西):

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

答案 1 :(得分:4)

如果类Team是实体,则无法在linq语句中创建它。您应该考虑创建自己的类并返回它。或者只是select t