我正在开发一个利用VS2013中的MVC4和EF Data First的项目。尝试将对象传递给视图时出现此错误。
传递到字典中的模型项的类型是' System.Data.Entity.Infrastructure.DbQuery
1[<>f__AnonymousType3
4 [System.String,System.Nullable1[System.Int32],System.Nullable
1 [System.Int32 ],System.Nullable1[System.Int32]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1 [TitansMVCWithBootStrap.Models.Player_Game_Stats]&#39;
我不知道如何解决这个问题,任何建议都会有所帮助。感谢
控制器
public class PlayerGameStatsController : Controller
{
private Context db = new Context();
// GET: PlayerGameStats/Details/5
public ActionResult Details(int gid=19, int sid = 11)
{
var playerGameStats = from pgs in db.PlayerGameStats
join p in db.Players on pgs.Player_id equals p.id_player
where pgs.SeasonId == 11 && pgs.GameNumber == 19
select new
{
p.PlayerName,
pgs.PlateAppearance,
pgs.Runs,
pgs.Hits
};
return View(playerGameStats);
}
模型
public class Player_Game_Stats
{
[Key]
[Column(Order = 0)]
public int Player_id { get; set; }
[Key]
[Column(Order = 1)]
public int GameNumber { get; set; }
public Nullable<int> PlateAppearance { get; set; }
public Nullable<int> Runs { get; set; }
public Nullable<int> HR { get; set; }
public int Hits{ get; set; }
//[ForeignKey("id_player")]
//public virtual Players Player { get; set; }
}
}
查看
@model IEnumerable<TitansMVCWithBootStrap.Models.Player_Game_Stats>
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Details</h2>
<table class="table table-striped">
<tr>
<th>
@Html.DisplayNameFor(model => model.PlayerName)
</th>
<th>
@Html.DisplayNameFor(model => model.PlateAppearance)
</th>
<th>
@Html.DisplayNameFor(model => model.Runs)
</th>
<th>
@Html.DisplayNameFor(model => model.Hits)
</th>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.PlayerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.PlateAppearance)
</td>
<td>
@Html.DisplayFor(modelItem => item.Runs)
</td>
<td>
@Html.DisplayFor(modelItem => item.Hits)
</td>
</tr>
}
</table>
也尝试了
var playerGameStats = (from pgs in db.PlayerGameStats
join p in db.Players on pgs.Player_id equals p.id_player
where pgs.SeasonId == 11 && pgs.GameNumber == 19
select new Player_Game_Stats
{
p.PlayerName,
pgs.PlateAppearance,
pgs.Runs,
pgs.Hits
}).ToList();
return View(playerGameStats);
答案 0 :(得分:0)
试试这个:
public ActionResult Details(int gid=19, int sid = 11)
{
var playerGameStats = from pgs in db.PlayerGameStats
join p in db.Players on pgs.Player_id equals p.id_player
where pgs.SeasonId == 11 && pgs.GameNumber == 19
select new TitansMVCWithBootStrap.Models.Player_Game_Stats
{
PlayerName = p.PlayerName,
PlateAppearance = pgs.PlateAppearance,
Runs = pgs.Runs,
Hits = pgs.Hits
};
return View(playerGameStats);
}