In System.Linq.Dynamic.Select (), how to deal with a null object reference in simple form?
I am using dynamic LINQ (System.Linq.Dynamic) (you can find a description here http://dynamiclinq.azurewebsites.net/GettingStarted ).
The following statement works well
Products.Select("new(ProductName, CategoryID.CategoryName as CategoryName)");
But I accidentally discovered that when CategoryID is null, the results are empty. But I suppose it will return a record like:
ProductName = "Wine", CategoryName = "" (or null).
Then I found a way to do it with
Products.Select("new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)");
The statement is ugly.
Do you have a better solution?
Thank you in advance,
+3
source to share
1 answer
The only thing I found is here . It's not clear why the decision was made, but I saw that you can do this:
"new(ProductName, iif(CategoryID==null,null,CategoryID.CategoryName) as CategoryName)"
instead of this:
"new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)"
It's not shorter, but for me it makes the code more readable because you're just using null
quotes instead of escaping.
+3
source to share