how to bind data from entityframework to datagrid?

I have 2 tables Customer and Order customer id is a primary key and it has foriegn key relationship with order key. so i want to display customers in datagrid and orderd in RowDetailsTemplate which consists of another datagrid.

Below is the XAML

   <Grid>
        <DataGrid AutoGenerateColumns="True" Name="dataGrid1">
            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <DataGrid ItemsSource="{Binding Order}" AutoGenerateColumns="True"/>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
        </DataGrid>
    </Grid>

In the codebehind i write the following code

    public MainWindow()
    {
        InitializeComponent();
        SampleDBEntities1 context = new SampleDBEntities1();
        dataGrid1.ItemsSource = context.Customers.ToList();           
    }

Here i am unable to bind the inner datagrid.

Below is the Context class

public partial class SampleDBEntities1 : DbContext
{
    public SampleDBEntities1()
        : base("name=SampleDBEntities1")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<Customer> Customers { get; set; }
    public DbSet<Order> Orders { get; set; }
}

Below are Entityframework generated classes for customer and order

public partial class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }

    public virtual Order Order { get; set; }
}

public partial class Order
{
    public int ID { get; set; }
    public string Number { get; set; }

    public virtual Customer Customer { get; set; }
}

Answers


You need to tell Entity Framework to eager-load the orders, otherwise it won't load them...

dataGrid1.ItemsSource = context.Customers.Include("Order").ToList();

Or

dataGrid1.ItemsSource = context.Customers.Include(c => c.Order).ToList();

(Need to add using System.Data.Entity;)

It should also work if removed the .ToList(), but it would lazy-load orders for each customer and you'd end up with a Select(n+1) problem.


Need Your Help

How do you get model metadata from inside a ValidationAttribute?

asp.net-mvc validation reflection data-annotations

MVC2 comes with a nice sample of a validation attribute called "PropertiesMustMatchAttribute" that will compare two fields to see if they match. Use of that attribute looks like this:

VS2008 Unit Test Project bugs

visual-studio visual-studio-2008 unit-testing

I'm using VS 2008 Developer Edition and am finding some bugs with the Test Projects.