LINQ to Entities不识别方法';Int32 IndexOf(Int32)'

本文关键字:Int32 to IndexOf Entities 识别 方法 LINQ | 更新日期: 2023-09-27 18:00:49

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是从teamDrawPIDs中的ID创建的,我就会得到这个错误(在视图页面上,控制器很好(:

"LINQ to Entities无法识别方法"Int32 IndexOf(Int32(">

LINQ to Entities不识别方法';Int32 IndexOf(Int32)'

根据错误,使用IndexOf()的表达式无法转换为Sql。你可以尝试一些更Sql友好的东西,比如:

entityDB.Players.Where(t => teamDrawPIDs.Contains(t.PID))
                .OrderBy(p => p.Last)

您也可以使用一些linq来消除for each,例如在一个步骤中:

var teamDrawPIDs = teamDrawPlayers.Select(tp => tp.PID).ToList();

Entity Framework不支持直接转换。因此,在我的个人建议中,最好的做法是设置一个值为的变量,我们将使用过滤器来防止这种类型的问题。