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)
It will return an empty enumerable. It won't be null.
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.
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.
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.
there is known pattren (see Null object pattern). Also you can read this article
Now you can do
var filteredOrders = myOrders.Where(x =>
x.Item?.Product?.Company?.Name == "Company1");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With