“could not instantiate” NHibernate.QueryException Raise By Combined Linq Query

StackOverflow https://stackoverflow.com/questions/3998247

  •  10-10-2019
  •  | 
  •  

سؤال

Executing the following NHibernate.Linq statement raises a "could not instantiate: Reservation001.Services.ReservationDto" NHibernate.QueryException containing an inner InvalidCast exception ("Object must implement IConvertible."):

var inOneStep = (from r in session.Linq<Models.ReservationHeader>()
    select new ReservationDto(r.Current));
return inOneStep;

However, after splitting the above into two queries, with ToList() called on the results of the first, the code executes fine.

var step1 = (from r in session.Linq<Models.ReservationHeader>()
     select r).ToList();
var step2 = from z in step1
     select new ReservationDto(z.Current);
return step2;

Why does the single statement version raise an exception?

Thank you,
Ben

هل كانت مفيدة؟

المحلول

The reason that the first one does not work is because the whole query is getting sent to NHibernate, and (as the exception tells you) NHibernate expects something with ReservationDto to be IConvertible.

The two step process avoids this error, because by calling "ToList()" you cause the query to execute in NHibernate immediately without involving ReservationDto, and returning an object collection. Your second step is then simply operating on an object collection, and since NHibernate is no longer involved, you avoid the error.

In general, Linq uses delayed execution, with a few functions (such as ToList() ) forcing immediate evaluation. See http://devlicio.us/blogs/derik_whittaker/archive/2008/04/07/linq-and-delayed-execution.aspx

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top