Max in linq to NHibernate for not exist data in database
Asked Answered
L

2

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?

Lancaster answered 12/6, 2012 at 13:45 Comment(0)
S
13

Try this

SessionInstance.Query<Request>().Max(x => (int?)x.Code);
Sheepskin answered 12/6, 2012 at 14:0 Comment(4)
Why does the cast make this work? Was x.Code something else than int?? (I just want to learn, not promoting my own answer).Commonable
@GertArnold I don't know, it just works:) But i think that it is something related to Nhibernate linq provider.Sheepskin
Ok, thanks for your response. Maybe someone can shed some light on this.Commonable
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.Obliterate
C
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>).

Commonable answered 12/6, 2012 at 14:18 Comment(4)
Your solution for many records in database for performance is not suitable.Lancaster
Why not? DefaultIfEmpty will not fetch more records, it will only add a value if the sequence is empty.Commonable
DefaultIfEmpty for NHibernate linq provider is not implemented and throws exception as of NHibernate 3.3.1.4000 versionParrakeet
Indeed - "The DefaultIfEmptyResultOperator result operator is not current supported"Microcosm

© 2022 - 2024 — McMap. All rights reserved.