错误:无法在 LINQ to Entities 查询中构造实体或复杂类型
我收到此错误“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>
<% } %>
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>
<% } %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于您正在
select
语句中创建一个Team
类,而 LINQ to SQL 不支持该类。将您的select
更改为:或使用匿名类型:
或使用 DTO(任何非实体):
The problem is that you are creating a
Team
class in aselect
statement, which is not supported by LINQ to SQL. Change yourselect
to:or use an anonymous type:
or use a DTO (anything that is not an entity):
如果类
Team
是一个实体,则无法在 linq 语句内创建它。您应该考虑创建自己的类并返回它。或者也许只是选择t
。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 justselect t
.