Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 722
musefan Avatar asked Feb 27 '12 11:02

musefan


People also ask

Will LINQ select return null?

It will return an empty enumerable. It won't be null.

Is null SQL in LINQ?

NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false". Save this answer.

Is null in LINQ C#?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.

On which datasources do LINQ queries work?

In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.


2 Answers

there is known pattren (see Null object pattern). Also you can read this article

like image 125
Lonli-Lokli Avatar answered Sep 23 '22 15:09

Lonli-Lokli


Now you can do

var filteredOrders = myOrders.Where(x => 
    x.Item?.Product?.Company?.Name == "Company1");
like image 45
codeMonkey Avatar answered Sep 23 '22 15:09

codeMonkey