Search code examples
c#linqlinq-to-sql

Automatically checking for NULL relationships with LINQ queries


I am using LINQ to SQL to handle the database querying for an application I am working on.

For the purposes of this example, imagine I have some tables like so

- Company
- Product
- Item
- Order

and lets say a Company has 0 or more Products, a Product has 0 or more Items, and an Item has 0 or more Orders.

Now lets so I have obtained a list of Orders, something like:

IQueryable<Order> myOrders = GetMyOrders();

Now lets say I want to query the orders for a particular Company.Name, but have a situation where each table parent ID can be NULL (I know this doesn't seem logical with my example data but it is just an example)

Making the assumption that there are no NULL parent IDs I could do this:

var filteredOrders = myOrders.Where(x => x.Item.Product.Company.Name == "Company1");

This would work fine, however, because there could be NULL parent ID values, I need to check each parent object to ensure it is not null before querying the next parent (otherwise I will get an exception). So I do something like:

var filteredOrders = myOrders.Where(x => 
    x.Item != null &&
    x.Item.Product != null &&
    x.Item.Product.Company != null &&
    x.Item.Product.Company.Name == "Company1");

So my question: Is there a better way (in terms of readability and ease of coding) to do this than having to include all the null checks? Any null parents found along the way should result in exclusion from the resulting list.

Please no suggestions for preventing null parents, the database will not be changing (and is perfectly valid anyway)


Solution

  • Now you can do

    var filteredOrders = myOrders.Where(x => 
        x.Item?.Product?.Company?.Name == "Company1");