0

I'm struggling with NHibernate to achieve a simple join.

Here is what i have :

Post.cs :

public class Post
{
    public virtual int id { get; set; }
    public virtual string user { get; set; }
    public virtual string message { get; set; }
}

public class PostMap : ClassMapping<Post>
{
    public PostMap()
    {
        Table("post");

        Id(x => x.id, map => { map.Column("id"); });
        Property(x => x.user, map => { map.Column("user"); });
        Property(x => x.message, map => { map.Column("message"); });
    }
}

User.cs :

public class User
{
    public virtual int id { get; set; }
    public virtual string user_identifier { get; set; }
    public virtual string username { get; set; }
}

public class UserMap : ClassMapping<User>
{
    public UserMap()
    {
        Table("user");

        Id(x => x.id, map => { map.Column("id"); });
        Property(x => x.user_identifier, map => { map.Column("user_identifier"); });
        Property(x => x.username, map => { map.Column("username"); });
    }
}

As you can see, i have 2 "entity" post and user . Posts have a user column that represent the user_identifier.

Here is how i get all the post from my database for now :

// CriteriaGenerator is only used here to create a criteria object based on filters in the filter object
ICriteria crit = CriteriaGenerator.GenerateCriteria<Post>(session, filters);

IList<Post> posts= crit.List<Post>();

With this, i get a list of post objects, and each of them, in the user member have the user_identifier value.

I would like to change this behavior to be able to Join the User table in my query, to get the list of post where the "user" member of each post is replaced by the username of the user.

Can hibernate do that ?

Nicolas Pretot
  • 182
  • 2
  • 12

1 Answers1

0

NHibernate has some queries API's, only one can support join between unrelated entities:

from user in session.Query<User>() 
join post in session.Query<Post>() 
on user.user_identifier equals post.user

For more information you can see here.

Or using subqueries like this.

Or add the references between entities like this.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Najera
  • 2,869
  • 3
  • 28
  • 52