0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.