NiaziBro NiaziBro - 7 days ago 5
C# Question

How to fill WPF DataGridView from related tables using LINQ query?

I am trying to fill my WPF dataGridView from two related tables using LINQ to Entity model.
Trying to Display these two tables

enter image description here

Expected Output:

enter image description here

But the BatchName column is not displaying any data. I am using following LINQ query:

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;
}


My DatagridView XML code:

<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>


This is how I am filling datagridview:

dg.ItemsSource = new StudentFactory().SelectNamesAndBatches();


Please guide me about what I might be doing wrong?

Answer

NiazBro, try this:

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;

This assumes that your Students model expresses this one to many link with Batches.

Comments