gpt4 book ai didi

linq-to-sql - 错误: The entity or complex type cannot be constructed in a LINQ to Entities query

转载 作者:行者123 更新时间:2023-12-04 08:15:01 26 4
gpt4 key购买 nike

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

Controller :

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

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

最佳答案

问题是您正在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
};

关于linq-to-sql - 错误: The entity or complex type cannot be constructed in a LINQ to Entities query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7215354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com