如何检索模型中的列表?
这就是我正在尝试的:
private void cbxPlayers_SelectedValueChanged(object sender, EventArgs e)
{
List<Record> records = new List<Record>();
string selectedPlayer = cbxPlayers.SelectedItem.ToString();
using (ProgressRecordContext context = new ProgressRecordContext())
{
records = (from Player in context.Players
where Player.Name == selectedPlayer
select Player.Records).ToList<Record>();
}
}
但是,这不起作用,我错过了什么?
这些是需要时的模型:
public class Player
{
[Key][DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AccountNumberId { get; set; }
public string Name { get; set; }
public virtual List<Record> Records { get; set; }
}
public class Record
{
public int RecordId { get; set; }
public int AccountNumberId { get; set; }
public double Level { get; set; }
public int Economy { get; set; }
public int Fleet { get; set; }
public int Technology { get; set; }
public int Experience { get; set; }
public DateTime TimeStamp { get; set; }
public virtual Player Player { get; set; }
}
编辑:这是错误消息:
错误 1“System.Linq.IQueryable>”不包含“ToList”的定义,并且最佳扩展方法重载“System.Linq.ParallelEnumerable.ToList(System.Linq.ParallelQuery)”有一些无效参数
错误 2 实例参数:无法从“System.Linq.IQueryable>”转换为“System.Linq.ParallelQuery”
编辑:
我看到我可能不太清楚我想要做什么。我最终想出了一种方法来做我想做的事,这就是:
private void cbxPlayers_SelectedValueChanged(object sender, EventArgs e)
{
lstvRecords.Items.Clear();
if(cbxPlayers.SelectedIndex == -1)
{
return;
}
string selectedPlayer = cbxPlayers.SelectedItem.ToString();
using (ProgressRecordContext context = new ProgressRecordContext())
{
var records = from Player in context.Players
from Record in context.Records
where Player.Name == selectedPlayer &&
Player.AccountNumberId == Record.AccountNumberId
select new
{
Level = Record.Level,
Economy = Record.Economy,
Fleet = Record.Fleet,
Technology = Record.Technology,
Experience = Record.Experience,
TimeStamp = Record.TimeStamp
};
foreach (var element in records)
{
string[] elements = {element.Level.ToString(),
element.Economy.ToString(),
element.Fleet.ToString(),
element.Technology.ToString(),
element.Experience.ToString(),
element.TimeStamp.ToString()
};
ListViewItem lvi = new ListViewItem(elements);
lstvRecords.Items.Add(lvi);
}
}
}
有没有更好的方法来编写该查询,或者我这样做的方式是否正确?