Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Join Two Tables In Nhibernate

List<object[]> olist = null;

olist = (_session.CreateQuery("Select pc.Id as Id, " + 
    "pct.DescEn as DescEn,pct.DescAr as DescAr, pc.ContentEn as ContentEn," + 
    "pc.ContentAr as ContentAr " + 
    "from ProjectCharter pc,ProjectCharterTemplate pct " + 
    "where pct.Id=pc.PRC_PCT_ID " + 
    "and pc.PRC_PRJ_ID=1")
.List<object[]>())
.ToList<object[]>();

This is My Query, I want to join two tables and get an output, when i run this is the db i get the perfect answere, but when i run it through c# with nhibernate mapping. i get errors.

Can i query this way or is there any other method to join two tables.

Thanks in advance.

like image 870
Hudhaifa Yoosuf Avatar asked Feb 26 '15 09:02

Hudhaifa Yoosuf


1 Answers

This is easy. Suprisingly easy. Check the

  • 15. Criteria Queries or
  • 16. QueryOver Queries API.

So, the above query in QueryOver could look like this:

// alias for later use
ProjectCharter project = null;
ProjectCharterTemplate template = null;

var list = session
    .QueryOver<ProjectCharter>(() => project)
    // the JOIN will replace the WHERE in the CROSS JOIN above
    // it will be injected by NHibernate based on the mapping
    // relation project has many-to-one template
    .JoinQueryOver<ProjectCharterTemplate>(c => c.Templates, () => template)
    .Select(
        // select some project properties
        _ => project.ContentEnglish,
        ...
        // select some template properties
        _ => template.DescriptionEnglish,
     )
    .List<object[]>();
like image 67
Radim Köhler Avatar answered Sep 21 '22 12:09

Radim Köhler