2011-08-27 35 views
6

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

控制器:

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

回答

10

问题是您在select语句中创建了Team类,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 
}; 
+0

谢谢你的详细解答! – Tsarl

4

如果类Team是它不能在linq语句中创建它。你应该考虑创建你自己的类,然后返回。或者也许只是select t

+0

感谢您的正确答案。 – Tsarl

+1

任何人都可以详细解释原因吗? –

相关问题