1

I have a problem querying using nHibernate.
I have the following entities:

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;}  
}  

I want to query using some sql like the following:

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  

Can any one help me please.

3
  • Sadly for you, the QueryOver syntax doesn't have support for math operations. You'll have to do horrible things like stackoverflow.com/questions/4828552/… Commented Aug 29, 2013 at 10:17
  • And I hope your Code(s) are int, otherwise I don't know how you could multiply it. Commented Aug 29, 2013 at 10:28
  • What did you try? HQL? Criteria? Linq? Commented Aug 29, 2013 at 11:10

2 Answers 2

2

As I've written, NHibernate QueryOver has poor syntax for math operations... Now, if we consider Code to be an int (because I normally don't multiply strings by 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();

The trick for math operations was taken from https://stackoverflow.com/a/10756598/613130

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you can check this question Fluent Nhibernate inner join

Or maybe from this explanation can guide you to find the right answer. http://ayende.com/blog/4023/nhibernate-queries-examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.