Question

I'm using Dynamic LINQ with NHibernate. Simple example demonstrates my problem:

var q = sess.Query<User>().Select("new (Id, Login, Person.Id as PersonId)");

throws NullReferenceException when where are Users in database with User.Person == null.

This solves the problem:

var q = sess.Query<User>().Select(new { Id, Login, PersonId = (long?)Person.Id });

but I need something like

var q = sess.Query<User>().Select("new (Id, Login, (long?)Person.Id as PersonId)");

because select expression is generated dynamically. Unfortunately dynamic LINQ does not understand cast to (long?) :(

What should I have to do? Thanks in advance!

==== Edit ====

Ok, I understood two things: 1. Dynamic LINQ does not know about long, only Int64. 2. Cast is not '(Int64)something' but 'Int64(something)'. So whole my code should be

sess.Query<User>().Select("new (Id, Login, Int64?(Person.Id) as PersonId)");

But it still does not solve my whole problem because NHibernate now fails with Could not execute query[SQL: SQL not available] exception and NullReference inner exception.

Was it helpful?

Solution

Finally I have mastered the problem. I studied Dynamic.cs and found that the Dynamic LINQ's syntax is very specific. Particularly the string expression "SomeType(SomeExpression)" generates cast expression only if SomeType has no constructor with one parameter. In other case it generates "new SomeType(SomeExpression)". I considered it as a mistake and slightly modified the Dynamic.cs.

Now in my example the cast can be made as 'Int64? Person.Id'. It is not a "normal" cast syntax but it works for me like a charm. Dynamic ExpressionParser is pretty good but unfortunately is not well adapted for C# cast syntax.

Also I registered in Dynamic.cs short type names like "long", "int" etc.

The modified source is downloadable here: http://1drv.ms/1cRJtSP .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top