2011-08-27 32 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

任何人都可以詳細解釋原因嗎? –

相關問題