NHibernate - join without a mapping
-
13-10-2019 - |
Question
I'm aware that similar question have been asked here and here and it could probably be a duplicate.
But the question has not been answered in both the places properly so reluctantly, I have to ask it again :(
The question is can you use Criteria API to join two tables when there is no mapping available between them.
E.g
class Order{ UserId , OrderId}
class User{UserId , UserName}
and I need to produce a query like,
select user.UserName , order.OrderId from Order order join User user on order.UserId = user.UserId
Please help if anyone is aware of this..and please do note that I need to do it using Criteria or QueryOver techniques
Thanks /BB
Solution
Here is an idea on how it can be done but it is a bit ugly.
Since the mapping does not state that the relationship between Order and User exists therefore it is pretty difficult to have NHibernate generate a join between these two tables. What you can do instead is do an inner select so your query as SQL would look like this:
SELECT o.OrderId, o.WhateverOtherPropertyNameFromOrder
(SELECT u.UserName, u.WhateverOtherPropertyNameFromUser
FROM User u
WHERE u.UserId = o.UserId)
FROM Order o
This can be done like this on QueryOver:
Order order = null;
User user = null;
QueryOver<User> query = QueryOver.Of<User>(() => user)
.Select(Projections.ProjectionList()
.Add(Projections.Property<User>(x => x.UserName)))
.Add(Projections.Property<User>(x => x.WhateverOtherPropertyNameFromUser)))
.Where(Restrictions.EqProperty("user.Id", "order.UserId"));
var result = session.QueryOver<Order>(() => order)
.Select(Projections.ProjectionList()
.Add(Projections.Property<Order>(c => c.OrderId))
.Add(Projections.Property<Order>(c => c.WhateverOtherPropertyNameFromOrder))
.Add(Projections.SubQuery(query)))
.List<object[]>();
I have no idea if this is useful at all to you but it is a potential solution to your problem.