Ivan Aramazov
Ivan Aramazov

Reputation: 167

WPF DataBinding ForeignKey value not dispalyed

I'm trying to display foreing key values in WPF DataGrid. Problem is when I load the window, the datagrid field stays empty. But when I insert or update data(operation happens in separate window), and the datagrid is refreshed, the values are displayed properly.

This is how i bind it:

<DataGridTextColumn Header="Team" Binding="{Binding Team.TeamName}"/>

DataGrid control is in EmployeesWindow.xaml This is the table with the foreign key:

 public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    //..
    [ForeignKey("Team")]
    public int TeamId { get; set; }
    public Team Team { get; set; }
}

And this is the table that is being referenced

public class Team
{
    [Key]
    public int TeamId { get; set; }
    public string TeamName { get; set; }
    public int TeamBonus { get; set; }        
}

In EmployeesWindow.xaml:

public static DataGrid datagrid;
public EmployeesWindow()
    {
        InitializeComponent();
        datagrid = EmployeeDataGrid;
        datagrid.ItemsSource = _db.Employees.ToList();
    }

In TeamsWindow.xaml:

 private void AddEmployee_Click(object sender, RoutedEventArgs e)
    {
        //..
        EmployeesWindow.datagrid.ItemsSource = _db.Employees.ToList();
        this.Hide();
    }

How can I display the foreign key value in WPF DataGrid data-binding?

Upvotes: 0

Views: 53

Answers (1)

Andy
Andy

Reputation: 12276

I guess this is entity framework you're using and _db is a dbcontext.

EF uses lazy loading of related tables by default.

Take a look at the sql your linq will produce.

How do I view the SQL generated by the Entity Framework?

I expect you will find that _db.Employees.ToList(); just gives something like "select * from Employees".

You need to explicitly tell it to read Teams as well.

Assuming the name of the table is Teams that would be:

datagrid.ItemsSource = _db.Employees.Include("Teams").ToList();

Don't just paste that in and hit f5. Check what your table name is and what sql it will produce.

Every time you use linq, get used to checking the sql it produces. With simple stuff like this you should instantly see no inner join to Teams in your original query. With more complicated stuff you can easily find LINQ produces terrible sql.

http://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx

https://learn.microsoft.com/en-us/ef/ef6/querying/related-data

As an aside.

Architecturally, reading an entire table out the database and presenting directly to the UI is bad in several ways. Maybe this is just prototype stuff and you're going to use a viewmodel, observablecollection, mvvm, tolistasync and filter your 200,000 employees down in the production version though.

Upvotes: 1

Related Questions