如何使用LINQ查询从相关表中填充WPF DataGridView?
问题描述:
我想从两个相关的表中使用LINQ to Entity模型来填充我的WPF dataGridView。 试图显示这两个表如何使用LINQ查询从相关表中填充WPF DataGridView?
预期输出:
但时将BatchName列不显示任何数据。我使用下面的LINQ查询:
public List<StudentViewModel> SelectNamesAndBatches()
{
var students = (from s in db.Students
join b in db.Batches
on s.BatchId equals b.Id
select new StudentViewModel
{
Name = s.Name,
Gender = s.Gender,
Age = s.Age,
BatchId = b.Id,
BatchName = b.BatchName
}).ToList();
return students;
}
我datagridview的XML代码:
<DataGrid Name="dg" AutoGenerateColumns="False" Width="500" Height="200" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="100" Binding="{Binding Name}">
</DataGridTextColumn>
<DataGridTextColumn Header="Age" Width="50" Binding="{Binding Age}">
</DataGridTextColumn>
<DataGridTextColumn Header="Gender" Width="100" Binding="{Binding Gender}">
</DataGridTextColumn>
<DataGridTextColumn Header="Batches Name" Width="100" Binding="{Binding Batches.BatchName}">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
这是怎么了填充的DataGridView:
dg.ItemsSource = new StudentFactory().SelectNamesAndBatches();
请指导我什么,我可能会做错误?
答
NiazBro,试试这个:
var students = (from s in db.Students.Include("Batches")
select new StudentViewModel
{
Name = s.Name,
Gender = s.Gender,
Age = s.Age,
BatchId = s.Batches.Id,
BatchName = s.Batches.BatchName
}).ToList();
return students;
这是假设你的学生模型表示这个人跟批次多个环节。
谢谢@Ibrahim,经过一番改变后,它工作。你能给我一个与此相关的教程链接吗?我无法理解这些东西。 – NiaziBro
Niaz ...看看这个:http://www.entityframeworktutorial.net/ –