1
我想使用實體框架將2個相關表(Northwind數據庫,Orders和Orders_Details表)加載到兩個CollectionView中。通過CollectionViewSource加載2個相關表
<Window.Resources>
<CollectionViewSource x:Key="OrdersView" />
<CollectionViewSource x:Key="OrdersDetailView"
Source="{Binding Source={StaticResource OrdersView},
Path='Order_Details'}" />
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource OrdersView}}">
<Grid.RowDefinitions>
<RowDefinition Height="187*" />
<RowDefinition Height="124*" />
</Grid.RowDefinitions>
<StackPanel>
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}" Height="187" HorizontalAlignment="Left" Name="dataGrid1" VerticalAlignment="Top" Width="503"/>
</StackPanel>
<StackPanel Grid.Row="1">
<DataGrid AutoGenerateColumns="True" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource OrdersDetailView}}" Height="124" HorizontalAlignment="Right" Name="dataGrid2" VerticalAlignment="Top" Width="503" />
</StackPanel>
</Grid>
public MainWindow()
{
InitializeComponent();
List<Order> list = new List<Order>();
using (NorthwindEntities nwe = new NorthwindEntities())
{
list = nwe.Orders.Include("Order_Details").ToList();
}
Window win = Application.Current.MainWindow;
var ordersViewSource = win.FindResource("OrdersView") as CollectionViewSource;
ordersViewSource.Source = list;
//var ordersDetailView = win.FindResource("OrdersDetailView") as CollectionViewSource;
}
當我運行這段代碼我得到一個異常:
的ObjectContext的實例已 配置並不能再被用於需要連接 操作。
編輯
如果我刪除它的工作使用的部分,但我想一切都加載到內存中,並關閉連接。
我厭倦了使用延遲加載:
using (NorthwindEntities nwe = new NorthwindEntities())
{
nwe.ContextOptions.LazyLoadingEnabled = true;
list = nwe.Orders.ToList();
}
沒有工作。