1

我在使用 nHibernate 进行查询时遇到问题。
我有以下实体:

public class CostAmount  
{  
    public virtual int Id {get;set;}  
    public virtual Year Year{get; set;}  
    public virtual Month Month{get; set;}  
}  

public class Year  
{  
    public virtual int Id {get;set;}  
    public virtual string Code {get;set;}  
}  

public class Month  
{  
    public virtual int Id {get;set;}  
    public virtual string Code {get;set;}  
}  

我想使用如下的一些 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  

任何人都可以帮助我。

4

2 回答 2

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

于 2013-08-29T10:32:46.783 回答
0

也许你可以检查这个问题Fluent Nhibernate inner join

或者也许从这个解释中可以指导你找到正确的答案。 http://ayende.com/blog/4023/nhibernate-queries-examples

于 2013-08-29T09:57:16.473 回答