Loading 2 relative tables via CollectionViewSource
I want to load 2 relative tables (Northwind databa开发者_StackOverflow社区se, Orders and Orders_Details tables) using entity framework into two CollectionView.
<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;
}
When I run this code I get an exception:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Edit
If I remove the Using part it works, but I want to load everything into memory and close the connection.
I tired to use lazy loading:
using (NorthwindEntities nwe = new NorthwindEntities())
{
nwe.ContextOptions.LazyLoadingEnabled = true;
list = nwe.Orders.ToList();
}
Didn't work.
it doesn't work because you use lazy loading!
if you want lazy loading, you need your datacontext, or how should your program know, what data you have loaded so far?
the NorthwindEntities object is not just a connection object. it is much more. and it opens a connection only if it is actually necessary.
if you really want to dispose it, turn lazy loading off.
精彩评论