开发者

Correct way to use a DataGrid when utilizing a LINQ2SQL DataContext table as its ItemsSource (best practices)

So, I am learning Linq2SQL by building a simple UI. I am using two DataGrids to display a master/details type interface, where "Customers" are displayed in one grid and, when selected, some details displayed in the other grid (for example, records from a foreign key table such as "Orders", whatever).

Now, every example I have read regarding the use of a DataGrid shows something like this:

using( var db = new TestDataContext() )
{
    // AutoGenerateColumns set to false and 
    // column bindings set to certain properties 
    // of the Customer class.
    grid.ItemsSource = db.Customers.ToList();
}

Well, that doesn't work because the DataContext is accessed after this code is executed due to data binding, and of course, the Context object has already been disposed. Ok, that's fine; I can use a single DataContext for all of my grid operations, even though the DataContext class was designed to be used and disposed of quickly. I'm not su开发者_开发问答re if keeping a single DataContext around is going to bite me in the future yet.

So now I run into the issue of updating the database and reflecting those changes back to the grid(s). The simplest way I have come across is to set ItemsSource to null and then bind it once again to the table. This just feels 'dirty' to me and I have to imagine I am missing something. In theory I could use an ObservableCollection and bind that to the grid, keeping it in sync with the underlying data, but I haven't yet figured out how to get the grid to display data from the observable collection (I bind it in XAML and only empty rows are rendered in the table).

TLDR:

So anyway, my question is this; what patterns do you experienced LINQ2SQL guys use for this type of a scenario? It seems that all of the examples I can find are overly simplistic and don't quite apply in a real world use case (even one as simple as mine). Basically, how do you use your DataContext, how do you keep the grid updated when new items are added to a table, and what are some general best practices here?


In the example code you provided, the datacontext would only be getting accessed again by bindings if you are binding to lazily loaded properties. Have you looked at the LoadOptions.LoadWith<>() function on the datacontext (assuming it hasn't been renamed since I last looked at linqtosql)

Personally I have no problem taking a hold of the datacontext and keeping it around for the page life, though not a single one for the whole application life.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜