Wednesday, 20 September 2017

NHibernate QueryOver distinct

Given the classes:
public class User
{
    public virtual int Id {get; set;}
    public virtual string UserName {get; set;}
}

public class UserRelationship
{
    public virtual int Id {get; set;}
    public virtual User GroupUser {get; set;}
    public virtual User MemberUser {get; set;}
}
And the fluent mappings of:
public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x=>x.Id).GeneratedBy.Native();
        Map(x=>x.UserName);
    }
}

public class UserRelationshipMap : ClassMap<UserRelationship>
{
    public UserRelationshipMap(){
        Id(x=>x.Id).GeneratedBy.Native();
        References(x=>x.GroupUser);
        References(x=>x.MemberUser);
    }
}
You want to retrieve a list of distinct "User" based on "MemberUser" from the UserRelationship class.
var distinctMemberUsers = QueryOver.Of<UserRelationship>()
    .Select(x => x.MemberUser.Id);

var users = QueryOver.Of<User>()
    .WithSubquery.WhereProperty(x=>x.Id).In(distinctMemberUsers)
This should use a In clause in the SQL to give you a distinct list of User.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive