I owe a big "Thank You" to
Matt Warren for sending me a solution to
my DLinq / Avalon problem. Matt sent me an email that said...
Your app creates a connection in a using scope (such that it is automatically disposed after the scope exists.) You also declare you query within that scope using a datacontext that is created referring to your connection. However, the query is not executed inside that scope, it is executed when it is enumerated. You are assigning this query to a UI element which will attempt to enumerate it when it is being displayed. Unfortunately, this is after you closed the connection.
DLINQ is trying to reopen the connection to get the data for you, however it looks like the connection is no longer usable after it has been disposed (at the end of the using scope.)
Solution: What you probably intended to do here is assign the results of the query to the UI element. You can do this easily by adding a call to
.ToList()
this.docPanelCustomers.DataContext = custs.ToList();
The call to ToList() will force the query to execute now.
Sure enough, just adding .ToList() did the trick!!!
protected override void OnLoading(System.EventArgs e)
{
using(SqlConnection connection = new SqlConnection(connectString))
{
DataContext db = new DataContext(connection);
connection.Open();
Table<Customer> Customers = db.GetTable<Customer>();
Table<Order> Orders = db.GetTable<Order>();
var custs =
from c in Customers
where c.CompanyName.StartsWith("A")
select new {
c.CustomerID,
c.CompanyName,
NumOrders =
c.Orders.Count
};
this.docPanelCustomers.DataContext = custs.ToList();
}
}