Книга: C# 2008 Programmer

Detecting Null Fields

Detecting Null Fields

Using the same query used in the previous section, let's modify it so that you can retrieve all customers living in the WA region:

var query1 =
 (from customer in ds.Customers
 where customer.Region=="WA"
 select new {
  customer.CustomerID,
  customer.CompanyName,
  customer.ContactName,
  customer.ContactTitle
 }).ToList();

When you execute the query, the program raises an exception. That's because some of the rows in the Customers table have null values for the Region field. To prevent this from happening, you need to use the IsNull() method to check for null values, like this:

var query1 =
 (from customer in ds.Customers
 where !customer.IsNull("Region") && customer.Region == "WA"
 select new {
  customer.CustomerID,
  customer.CompanyName,
  customer.ContactName,
  customer.ContactTitle
 }).ToList();

Notice that LINQ uses short-circuiting when evaluating the conditions in the where statement, so the IsNull() method must be placed before other conditions.

Interestingly, the Field() extension method handles nullable types, so you do not have to explicitly check for null values if you are not using typed DataSets.

Оглавление книги


Генерация: 1.283. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз