9

I have a query by linq to NHibernate.

var q = SessionInstance.Query<Request>().Max(e => e.Code);

If Request table has no rows, execution of this query raises GenericADOException with this message :

{"Could not execute query[SQL: SQL not available]"}

{"Value cannot be null.\r\nParameter name: item"}

What should I do?

Digbyswift
  • 10,310
  • 4
  • 38
  • 66
Ehsan
  • 3,431
  • 8
  • 50
  • 70

2 Answers2

13

Try this

SessionInstance.Query<Request>().Max(x => (int?)x.Code);
Marian Ban
  • 8,158
  • 1
  • 32
  • 45
  • Why does the cast make this work? Was `x.Code` something else than `int?`? (I just want to learn, not promoting my own answer). – Gert Arnold Jun 12 '12 at 14:31
  • @GertArnold I don't know, it just works:) But i think that it is something related to Nhibernate linq provider. – Marian Ban Jun 12 '12 at 14:37
  • 1
    Ok, thanks for your response. Maybe someone can shed some light on this. – Gert Arnold Jun 12 '12 at 14:40
  • 1
    Your Max function might return null if for example there is no rows in the database table, therefore you casting it properly `(int?)x.Code`. There's gonna be no difference in generated SQL. – Alex M Nov 28 '12 at 15:51
1

I think this should work with Linq-to-Nhibernate:

var q = SessionInstance.Query<Request>().Select(e => e.Code)
    .DefaultIfEmpty().Max();

or maybe DefaultIfEmpty(<some value>).

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291