NHibernate2 query is wired when fetch the collection from the proxy. Is this correct behavior?

Posted by ensecoz on Stack Overflow See other posts from Stack Overflow or by ensecoz
Published on 2009-01-02T14:46:20Z Indexed on 2010/03/27 7:03 UTC
Read the original article Hit count: 318

This is my class:

public class User
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }

    public virtual IList<UserFriend> Friends { get; protected set; }        
}

public class UserFriend
{
    public virtual int Id { get; set; }
    public virtual User User { get; set; }
    public virtual User Friend { get; set; }
}

This is my mapping (Fluent NHibernate):

public class UserMap : ClassMap<User>
{
  public UserMap()
  {
    Id(x => x.Id, "UserId").GeneratedBy.Identity(); 				
    HasMany<UserFriend>(x => x.Friends);                
  }
}

public class UserFriendMap : ClassMap<UserFriend>
{
    public UserFriendMap()
    {
        Id(x => x.Id, "UserFriendId").GeneratedBy.Identity();

        References<User>(x => x.User).TheColumnNameIs("UserId").CanNotBeNull();
        References<User>(x => x.Friend).TheColumnNameIs("FriendId").CanNotBeNull();
    }
}

The problem is when I execute this code:

User user = repository.Load(1);
User friend = repository.Load(2);

UserFriend userFriend = new UserFriend();
userFriend.User = user;
userFriend.Friend = friend;

friendRepository.Save(userFriend);

var friends = user.Friends;

At the last line, NHibernate generate this query for me:

SELECT
  friends0_.UserId as UserId1_,
  friends0_.UserFriendId as UserFrie1_1_,
  friends0_.UserFriendId as UserFrie1_6_0_, 
  friends0_.FriendId as FriendId6_0_, 
  friends0_.UserId as UserId6_0_ 
  FROM "UserFriend" friends0_ WHERE friends0_.UserId=@p0; @p0 = '1'

QUESTION: Why the query look very wired? It should select only 3 fields (which are UserFriendId, UserId, FriendId) Am I right? or there is something going on inside NHibernate?

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about fluent-nhibernate