In a dynamic LINQ expression, a Null Reference Exception occurs.

c# dynamic-linq linq


I'm arranging a list using the Microsoft Dynamic Linq Library / Sample. As an example, I have the C# code below:

         .OrderBy(sortField + " " + sortDirection).ToList();

I have a situation where my item has a 0:1 connection with another object, and that object has an attribute that might be shown in the grid. As long as this kid is present in all of my widgets, sorting this works as intended. According to, we areChild.Name for instance. However, we get the null reference exception when Child is null.

I know I can use some of these choices to create an anonymous type and bind to it. I can also expose the Child. I don't like having my object model compromised for this, therefore name on the parent object and manage this through code.

In a perfect world, I would upgrade the library to cope with this situation. Before I start, I want to know whether anybody has previously encountered this issue and has a solution.


It seems that my explanation was insufficient. The Dynamic Library for Linq that is included with the samples in C# is what I am utilizing. With the help of this library's handy enhancements, you may use a string instead of a lambda expression. Therefore, my code looks somewhat like this:

private  void BindGrid(sortField,sortDirection)

     this.grid.DataSource=....OrderBy("MyField ASC")....

Of course, the arguments are substituted for that string. However, this enables us to dynamically adjust the sorting when the user clicks on a grid heading. To handle all the possibilities, we don't need to use if then else logic.

My proposed solution, which I have described below, transforms my tidy approach into:

private void BindGrid()
   var sortField=this._sortField;
   if (sortField=="Child.Name")
                                  .OrderBy(sortField + " " + this._sortDirection)

Even though it works, I now have to adjust the code whenever I add new fields or properties that we want to make available in the grid but are located on a child object.

9/18/2009 4:45:32 PM

Accepted Answer

If I have understood you right, I believe you desire:

    .OrderBy(p => p.Child == null ? "" : p.Child.Name);

This expression will be able to be replicated in SQL through LINQ.

9/18/2009 2:49:31 PM

Popular Answer

Detecting when the expression is going to access the kid and changing the sort expression to be would be one approach I've discovered, however it's not perfect in my instance.

iif(Child == null,null,Child.Name) ASC

It would be ideal if this reasoning could be included into the dynamic library; I'd like not have to adjust each grid individually to address every situation this will affect.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow