Yoav
Yoav

Reputation: 2077

NHibernate - simple join query

A very simple scenario. I have 2 classes: Project and DataStructure. Class Project contains member List<DataStructure>. My goal is to load a Project and all its DataStructures in one call.

public class Project
{
    public virtual string Id { get { } set { } }
    public virtual string Name { get { } set { } }
    public virtual ISet<DataStructure> DataStructures { get { } set { } }
}

public class DataStructure
{
    public virtual string Id { get { } set { } }
    public virtual string Name { get { } set { } }
    public virtual string Description { get { } set { } }
    public virtual Project Project { get { } set { } }
    public virtual IList<DataField> Fields { get { } set { } }
}

Note that DataStructure also contains a list of class DataField but I don’t want to load these right now.

Mapping in Fluent NHibernate:

public class ProjectMap : ClassMap<Project>
{
    public ProjectMap()
    {
        Table("PROJECTS");
        Id(x => x.Pk, "PK");
        Map(x => x.Id, "ID");
        Map(x => x.Name, "NAME");
        HasMany<DataStructure>(x => x.DataStructures).KeyColumn("FK_PROJECT");
    }
}

public class DataStructureMap : ClassMap<DataStructure>
{
    public DataStructureMap()
    {
        Table("DATA_STRUCTURES");
        Map(x => x.Id, "ID");
        Map(x => x.Name, "NAME");
        Map(x => x.Description, "DESCRIPTION");
        References<Project>(x => x.Project, "FK_PROJECT");
        HasMany<DataField>(x => x.Fields).KeyColumn("FK_DATA_STRUCTURE");
    }
}

This is my query:

using (ISession session = SessionFactory.OpenSession())
{
    IQuery query = session.CreateQuery("from Project left join DataStructure");
    project = query.List<Project>();
}

The result is this exception:

NHibernate.Hql.Ast.ANTLR.SemanticException: Path expected for join! [from Themis.DataEntities.Project left join DataStructure]

Do I need to specify the field for the join? Isn’t that inferred from the mappings?

Note1 – Table PROJECTS contains a single Project row so there is no need to search for a specific one.

Note2 – I verified that my NHibernate setup is correct by successfully loading just the Project.

Upvotes: 2

Views: 4408

Answers (2)

Yoav
Yoav

Reputation: 2077

For anyone who is interested I found the answer on nhusers:

IQuery query = session.CreateQuery("from Project as pr left join pr.DataStructures")

Upvotes: 2

Egor Pavlikhin
Egor Pavlikhin

Reputation: 17981

Your query should be "from Project left join Project.Fields". Project.DataStructures is the path that NH expects to see. Remember that it's object oriented, not table oriented, so most of the time even your queries operate on objects.

Upvotes: 1

Related Questions