【发布时间】:2015-02-15 01:52:07
【问题描述】:
我正在尝试为我的垒球 Web 应用程序创建一个新的前五名热门排行榜。我是 MVC 的新手,我无法将此查询放在一起并将信息传递给我的 ViewModel。如果可能的话,我想在控制器中使用像“var results”这样的非查询调用。我正在尝试按 Stat 表中的 PlayerID 对 AtBats 进行分组。对于这个列表,我还希望能够从我的视图中的 Player 表中调用玩家的 FirstName 和 LastName。感谢您的帮助!
在 Stat.cs 中
using System;
namespace TheFlyingPig.Models
{
public class Stat
{
public int StatID { get; set; }
public int SeasonID { get; set; }
public int PlayerID { get; set; }
public DateTime GameDate { get; set; }
public int AtBats { get; set; }
public int Hits { get; set; }
public int Walks { get; set; }
public int Singles { get; set; }
public int Doubles { get; set; }
public int Triples { get; set; }
public int HomeRuns { get; set; }
public int RBIs { get; set; }
public int Runs { get; set; }
public int ReachedOnErrors { get; set; }
public int SacrificeFlies { get; set; }
public virtual Season Season { get; set; }
public virtual Player Player { get; set; }
}
}
在 Player.cs 中
using System;
using System.Collections.Generic;
namespace TheFlyingPig.Models
{
public class Player
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Stat> Stats { get; set; }
}
}
在 Season.cs 中
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace TheFlyingPig.Models
{
public class Season
{
public int SeasonID { get; set; }
public string SeasonName { get; set; }
public virtual ICollection<Stat> Stats { get; set; }
}
}
在 TeamStat.cs(我试图将这些数据推送到我的 ViewModel)中
//Get the season leaders from controller
public List<Stat> SeasonLeadersHits { get; set; }
我已经在我的控制器 (HomeController.cs) 中尝试了以下两个选项,但我似乎无法在此取得任何进展来获得团队的 Top 5 Hits 领导者。
var lastSeasonId = db.Seasons.OrderByDescending(u => u.SeasonID).Select(u => u.SeasonID).FirstOrDefault();
var leadersAtBats = (from s in db.Stats
join p in db.Players on s.PlayerID equals p.ID
where s.SeasonID == lastSeasonId
group s.Hits by s.PlayerID into g
order by s.Hits descending
select new { LeaderID = g.Key, LeaderList = g.ToList() })
.Take(5);
var results = db.Stats.Where(s => s.SeasonID == lastSeasonId).GroupBy(s => s.PlayerID, s => s.Hits, (key, g) => new { PlayerId = key, Hits = g.ToList() });
var view = new TeamStat() { SeasonLeadersHits = results };
return View(view);
【问题讨论】:
-
错误表示它无法将类型“System.Linq.IQueryable
”隐式转换为“System.Collections.Generic.List ”。存在显式转换(您是否缺少演员表?) -
您的属性是
List<Stat> SeasonLeadersHits,但您的所有查询都在创建匿名类型(select语句),而不是 typeofStat。 -
斯蒂芬,我在网上看到过这个解释,但我不明白如何解决它。我怎样才能将它添加到我的 TeamStat ViewModel 中?
标签: c# sql linq visual-studio-2013 asp.net-mvc-5