you may be experiencing what is caused by the closure principle. you reference the user property in your linq query. because the linq query in itself is executed as an (anonymous) method delegate, the closure principle applies.

quoting the above link:

in essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.

the usage of the user property is subject to this principle. its value can have changed upon the execution of the linq query. to protect against this, the user property should be copied to a local variable and that referenced in the linq query. like so:

var user = user;
var users = => m.from)
                   .union( =>
                   .where(u => !=


when using a local reference copy to the user property, another possibility for the nullreferenceexception may lie with the select-union-distinct methods. when calling tolist, the where clause is executed on all items in the union of the two select clauses. by default, distinct executes the equals method from the iquality interface, which would be called on the elements from select(m => m.from) . if this element is null, it would cause the nullreferenceexception.

Related Query

More Query from same tag