我有2个表Customer
和Order
客户ID是主键,它与订单键具有foriegn密钥关系。所以我想在datagrid中显示客户,并在RowDetailsTemplate中对其进行排序,其中包含另一个数据网格。
以下是XAML
<Grid>
<DataGrid AutoGenerateColumns="True" Name="dataGrid1">
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding Order}" AutoGenerateColumns="True"/>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</Grid>
在代码隐藏中,我编写以下代码
public MainWindow()
{
InitializeComponent();
SampleDBEntities1 context = new SampleDBEntities1();
dataGrid1.ItemsSource = context.Customers.ToList();
}
这里我无法绑定内部数据网格。
以下是Context类
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; }
}
以下是Entityframework为客户和订单生成的类
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; }
}
答案 0 :(得分:4)
您需要告诉Entity Framework急切加载订单,否则它们不会加载它们......
dataGrid1.ItemsSource = context.Customers.Include("Order").ToList();
或者
dataGrid1.ItemsSource = context.Customers.Include(c => c.Order).ToList();
(需要添加using System.Data.Entity;
)
如果删除.ToList()
,它也应该有效,但它会为每个客户延迟加载订单,并且最终会出现选择(n + 1)问题。