2013-08-29 188 views
1

我有一個問題,使用nHibernate查詢。
我有以下實體:nHibernate複雜查詢

​​

我想用一些SQL類似下面的查詢:

select * from CostAmount ca 
inner join Year y on ca.YearID = y.ID 
inner join Month m on ca.MonthID = m.ID 
where y.Code *100+m.Code between 9107 and 9207 

任何一個可以幫我請。

+0

不幸的是,QueryOver語法不支持數學運算。你將不得不做一些可怕的事情,像http://stackoverflow.com/questions/4828552/are-there-any-arithmetic-operation-projections-in-nhibernate – xanatos

+0

我希望你的代碼是'int',否則我不知道你會如何繁殖它。 – xanatos

+0

你嘗試了什麼? HQL?標準是什麼? LINQ? –

回答

2

正如我已經寫了,NHibernate的QueryOver對數學運算語法很差......現在,如果我們考慮Code是一個int(因爲我通常不乘以100的字符串):

// Aliases 
CostAmount costAmount = null; 
Year year = null; 
Month month = null; 

// Projections for the math operations 

// y.Code * 100 
var proj1 = Projections.SqlFunction(
    new VarArgsSQLFunction("(", "*", ")"), 
    NHibernateUtil.Int32, 
    Projections.Property(() => year.Code), 
    Projections.Constant(100) 
); 

// proj1 + m.Code 
var proj2 = Projections.SqlFunction(
    new VarArgsSQLFunction("(", "+", ")"), 
    NHibernateUtil.Int32, 
    proj1, 
    Projections.Property(() => month.Code) 
); 

// The query 

var query = Session.QueryOver(() => costAmount) 
        .JoinAlias(() => costAmount.Year,() => year) 
        .JoinAlias(() => costAmount.Month,() => month) 
        .Where(Restrictions.Between(proj2, 9107, 9207)); 

var res = query.List(); 

數學運算的訣竅取自https://stackoverflow.com/a/10756598/613130