5

I have a query using linq to NHibernate, for EnterAndExitArchive entity. This entity has a association by Archive entity.

public EnterAndExitArchive GetLastEnterAndExitArchive(long archiveId)
{
   var q = SessionInstance.Query<EnterAndExitArchive>()
          .Where(x => x.Archive.Id == archiveId)
          .LastOrDefault<EnterAndExitArchive>();

   return q;
}

Or

public EnterAndExitArchive GetLastEnterAndExitArchive(long archiveId)
{
   var q = SessionInstance.Query<EnterAndExitArchive>()
          .LastOrDefault<EnterAndExitArchive>(x => x.Archive.Id == archiveId);

   return q;
}

But this has a runtime error. Message of exception is The LastResultOperator result operator is not current supported.

Why?

Ehsan
  • 3,431
  • 8
  • 50
  • 70

2 Answers2

16

LastOrDefault() is not supported in NHibernate.

Maybe you could order the result and use FirstOrDefault() instead:

public EnterAndExitArchive GetLastEnterAndExitArchive(long archiveId)
{
   var q = SessionInstance.Query<EnterAndExitArchive>()
          .Where(x => x.Archive.Id == archiveId)
          .OrderByDescending(x => x.Something)
          .FirstOrDefault();

   return q;
}
dillenmeister
  • 1,627
  • 1
  • 10
  • 18
3

It seems the nhibernate Linq provider did not implement LastOrDefault() - as a result it is not supported. You can work around this by first of all establishing an order that will return the items you want in reverse order and then using FirstOrDefault() instead:

var q = SessionInstance.Query<EnterAndExitArchive>()
          .OrderByDescending(x=> x.SomeOrderField)
          .FirstOrDefault<EnterAndExitArchive>(x => x.Archive.Id == archiveId);

Also I see you are currently not ordering your results in your query at all - what order did you expect the results to be in? If the order is undefined LastOrDefault() is the same as FirstOrDefault() ;-)

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335