Reputation: 43311
Let's say I have the following code in WPF application:
try { // NorthwindDataContext is LINQ DataContext created for SQL Server Northwind database Data.NorthwindDataContext data = new Data.NorthwindDataContext(connectionString); var orders = from order in Data.Orders select order; listView.DataContext = orders; } catch (SqlException ex) { MessageBox.Show(ex.Message); }
If connectionString is incorrect, this code doesn't throw SqlException immediately. Instead of this, exception is thrown later, when WPF data binding starts to enumerate LINQ query. Application crashes with unhandled exception. How can I handle exception in such situation?
I know that it is possible with global exception handling, but I want more precise way, which allows to catch specific exception when specific function is executed.
Upvotes: 0
Views: 456
Reputation: 81660
This is the curse of the Linq and not data binding.
Your query has been compiled but not run - you are binding to a query not the result. Change to the following code:
var orders = from order in Data.Orders select order;
var realOrders = orders.ToList();
listView.DataContext = realOrders ;
Basically your repository must always return results and not raw queries.
Upvotes: 1