简体   繁体   中英

How to Subselect using NHibernate 2 and Fluent mapping with alias

I am maintaining a large stable. legacy system that is still on NHibernate 2.

NOTE: Unfortunately, there is no chance of an upgrade at this time, but it is planned for the future

I am trying to do a subselect when a particular item is searched.

I would like to generate something similar to the following SQL

SELECT
   u.Id,
   u.Name,
   u.Email,
   (SELECT TOP 1 FROM Notifications n WHERE n.UserId = u.Id ORDER BY DateSent DESC) AS LastNotification
FROM
   Users u

My for the subselect is as follows:

//...
Map(x => x.LastNotification).Formula("(SELECT TOP 1 FROM Notifications n WHERE n.UserId = this_.Id ORDER BY DateSent DESC)").ReadOnly();
//..

I used this_ to refer to the Users table, as it is generated by NHibernate

The problem arises when the User entity is a property of another related entity, so this_ becomes something else.

As expected, the SQL error is The multi-part identifier "this_.Id" could not be bound.

I have struggled to find a way of creating an alias and cant seem to find a solution I can use for my case..

How else can I do subselects in NHibernate 2?

Found the answer here. I had to remove this_ .

NHibernate will infer the current entity where the formula is defined.

https://stackoverflow.com/a/9515787/919426

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM