2014-02-24 100 views
2

試圖爲具有使得別名使用別名的值的列表的關係生成nhibernate查詢。JoinOverQuery與包含​​列表的多個表

用戶可以擁有多個角色或承租人,我想選擇具有特定角色和特定承租人的所有用戶。

我是迄今做的是不工作:

var query = Session.QueryOver<User>(); 

query.JoinQueryOver<Role>(x => x.Roles) 
    .WhereRestrictionOn(x => x.Id == roleId); 

query.JoinQueryOver<Tenant>(x => x.Tenants) 
    .WhereRestrictionOn(x => x.Abbreviation == Context.Abbreviation);  

這有什麼建議?當我嘗試使用別名時,遇到了需要使用.Contains方法的問題,並且我不認爲nhibernate/sql可以找出如何處理該問題。

這是當我碰上了第一JoinQueryOver

"message": "An error has occurred.", 
"exceptionMessage": "variable 'x' of type 'Role' referenced from scope '', but it is not defined", 
"exceptionType": "System.InvalidOperationException", 
+0

問題到底是什麼?或者你得到了什麼明顯的錯誤? – rae1

+0

對不起,最初應該做到這一點。現在把它扔了 – SomeoneRandom

回答

2

在這種情況下,語法,我得到的錯誤,一定是這樣的:

query.JoinQueryOver<Role>(x => x.Roles) 
    //.WhereRestrictionOn(x => x.Id == roleId) 
    .Where(x => x.Id == roleId) 
    ; 

WhereRestrictionOn可用於類似的場景這個:

.WhereRestrictionOn(() => role.Name) 
    .IsLike("Admin", MatchMode.Start) 

但是我會建議,如果可能的話,使用子查詢。 (如果集合項目具有參考父)

User user = null; 
Role role = null; 

// the subselect, filtering the Roles, returning the user ID 
var subQuery = QueryOver.Of<Role>(() => role) 
    .Where(() => role.ID == roleId) 
    .Select(c => role.User.ID); 


// the query of the User, 
// where at least one role fits the above subquery 
var query = session.QueryOver<User>(() => user) 
    .WithSubquery 
    .WhereProperty(() => user.Id) 
    .In(subQuery); 

在許多其他優點,這種做法會給我們一個平根User表,所以我們可以應用Skip()Take()正確分頁...

+0

謝謝,你說得對我濫用WhereRestrictionOn – SomeoneRandom

+0

好,如果有幫助。享受NHibernate,真棒工具;) –