NHibernate QueryOver to join unrelated entities

前端 未结 4 1543
我寻月下人不归
我寻月下人不归 2020-12-16 20:07

I have the following query working which gets the results I want:

int associatedId = 123;

MyObject alias = null;

var subQuery = QueryOver.Of

        
4条回答
  •  無奈伤痛
    2020-12-16 20:35

    I realize this question is 5 years old, and the "correct" answer is definitely that you can't do this with QueryOver, as the other answers indicate. However, if you really need this functionality (as I did), there is a decent workaround that I found.

    The solution is to use a "loader query" with native SQL in your mapping XML to produce a related collection (see http://nhibernate.info/doc/nhibernate-reference/querysql.html#querysql-load). In the OP's specific example, you would go ahead and map your DatabaseView as an entity as suggested, and then write the following in your mapping:

    
        ...
        
            
            
            
        
    
    

    Then we just need to define our named myObjectViewsLoadQuery in raw SQL to explain to NH how to join the two:

    
        
        SELECT view.*
        FROM DatabaseView view
        WHERE view.ObjectId = :id
    
    

    We can now pretend like there is a "real" collection named MyViews relating MyObject to DatabaseView in our query:

    MyObject alias = null;
    DatabaseView view = null;
    var results = session.QueryOver(() => alias)
         .JoinAlias( () => alias.MyViews, () => view )
         //.Where( () => view.Property == "myValue" ) // optionally, restrict the view etc.
         .List();
    

    Certainly, this is a lot of trouble to go through if you only care about an "elegant" query. However, if the reason you are using QueryOver is that you want to be able to accept arbitrary input Expressions to filter your DatabaseView by, or various similar activities, this works very nicely.

提交回复
热议问题