MVC5 / EF 6
在我看来
@Html.DropDownList("selectPlayer", (SelectList)ViewBag.Players, "Select Player", new { @class = "form-control" })
在我的控制器中:
if (Convert.ToInt32(mySession.Format) == 4)
{
List<Int32> teamDrawPIDs = new List<Int32>();
List<TeamDraw> teamDrawPlayers;
teamDrawPlayers = entityDB.TeamDraws.Where(t => t.TID == TID).ToList();
foreach (TeamDraw tPlayer in teamDrawPlayers)
{
teamDrawPIDs.Add(tPlayer.PID);
}
// only get players in TeamDraw
ViewBag.Players = new SelectList(entityDB.Players.Where(t => (teamDrawPIDs.IndexOf(t.PID) != -1)).OrderBy(p => p.Last), "PID", "selectListName");
}
else
{
ViewBag.Players = new SelectList(entityDB.Players.OrderBy(p => p.Last), "PID", "selectListName");
}
当mySession.Format
不是4时,这一切都正常。但是只要它是4,我的ViewBag.Players
仅从ID
中的teamDrawPIDs
创建,我得到此错误(在视图页面上,控制器很好):< / p>
&#34; LINQ to Entities无法识别方法&#39; Int32 IndexOf(Int32)&#39;&#34;
答案 0 :(得分:3)
根据错误,使用IndexOf()
的表达式无法转换为Sql
。您可以尝试更多Sql Friendly,例如:
entityDB.Players.Where(t => teamDrawPIDs.Contains(t.PID))
.OrderBy(p => p.Last)
你也可以使用一些linq消除for-each,例如一步到位:
var teamDrawPIDs = teamDrawPlayers.Select(tp => tp.PID).ToList();
答案 1 :(得分:0)
实体Frameworrk不支持直接强制转换。所以在我的个人建议设置变量时,我们将使用过滤器以防止此类问题。